Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return data as JSON in Sequelize

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.

like image 324
Andy Ray Avatar asked Apr 25 '15 18:04

Andy Ray


People also ask

How do I save JSON in Sequelize?

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') });

Does Sequelize query return a promise?

Promises and async/await​Most 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.

What is Sequelize FN?

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.

What is plain true?

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.


3 Answers

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
    }
}
like image 117
Hoverbear Avatar answered Oct 21 '22 14:10

Hoverbear


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.

like image 29
captainkirk Avatar answered Oct 21 '22 15:10

captainkirk


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

like image 3
Lucas Avatar answered Oct 21 '22 13:10

Lucas