Andy Ray
Andy Ray

Reputation: 32066

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.

Upvotes: 10

Views: 27639

Answers (3)

captainkirk
captainkirk

Reputation: 121

When you retrieve the model from the database, you can call the .get({ plain: true}) on the result, which 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.

Upvotes: 11

Hoverbear
Hoverbear

Reputation: 123

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
    }
}

Upvotes: 12

Lucas
Lucas

Reputation: 193

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

Upvotes: 3

Related Questions