How to return data as JSON in Sequelize

When I make a Sequelize request, it returns to me an object (or array), which I assume is a Sequelize model (or an array of models (collection type?)), But it is not documented anywhere, just guessing. I always like JSON results. Is there anything I can pass in the request to force this? I would prefer not to massage every result when I get back to be JSON if possible.

The documentation shows this to return a string:

console.log(JSON.stringify(users)) 

So there is built-in serialization. Now I am 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.

+6
source share
3 answers

You can use raw: true in the query, but 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 when you use associations, you can get something like this:

 { foo: true, "associated.bar": true } 

Instead of what you can expect:

 { foo: true, associated: { bar: true } } 
+8
source

When you retrieve a model from the database, you can call .get({ plain: true}) as a result and handle the conversion for you. You can assign the value of a function call to a variable. for instance

..).then(function(user){ var _user = user.get({ plain: true}); console.log(_user); //Should be valid json object });

Hope this helps.

+6
source

If you are executing a query with multiple results, you should expect the array to return. You should find that every element in the result array is a JSON object.

You must have access to the specified field as follows: result[0].myfieldname

+2
source

Source: https://habr.com/ru/post/985962/


All Articles