When I make a Sequelize query it returns to me an object (or array) which I'm guessing is a Sequelize model (or array of Models (a collection type??)) but it's not documented anywhere, so I'm just guessing. I would always like the results to be JSON. Is there anything I can pass in the query to force this? I would prefer not to hand massage every result I get back to be JSON if possible.
The documentation show this to return a string:
console.log(JSON.stringify(users))
So there's some built in serialization. Right now I'm doing this, using the undocumented toJSON()
method:
query().then(function(result) {
if(result.length) {
return result.toJSON();
} else {
return result.map(function(item) {
return item.toJSON();
});
}
});
which is cumbersome.
Create a database and a Schema: var Sequelize = require('sequelize'), JsonField = require('sequelize-json'), db, User; db = new Sequelize('database', 'username', 'password', { dialect: 'sqlite', logging: false }); User = db. define('User', { username: Sequelize. STRING, jsonField: JsonField(db, 'User', 'jsonField') });
Promises and async/awaitMost of the methods provided by Sequelize are asynchronous and therefore return Promises. They are all Promises , so you can use the Promise API (for example, using then , catch , finally ) out of the box.
Function fnCreates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. If you want to refer to columns in your function, you should use sequelize.
DEFINITIONS1. used for saying what you think is true even if it offends someone. The plain fact is that he is not doing his job very well.
You can use raw: true
in the Query however this does not always behave as you might expect, especially with associations.
query({
// ...
raw: true
}).then(function(result) {
// Result is JSON!
});
However in the case where you're using associations you may get something like this:
{
foo: true,
"associated.bar": true
}
Instead of what you might expect:
{
foo: true,
associated: {
bar: true
}
}
When you retrieve the model from the database, you can call the .get({ plain: true})
on the result and it will handle the conversion for you. You can assign the value of the function call to a variable. For example
..).then(function(user){
var _user = user.get({ plain: true});
console.log(_user); //Should be valid json object
});
Hope this helps.
If you're doing a query with which has multiple results you should expect an array to be returned. You should find that each element in the result array is a JSON object.
You should be able to access a given field like this: result[0].myfieldname
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With