Sequelize, convert entity to plain object
Best and the simple way of doing is :
Just use the default way from Sequelize
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw : true // <----------- Magic is here
}).success(function (sensors) {
console.log(sensors);
});
Note : [options.raw] : Return raw result. See sequelize.query for more information.
For the nested result/if we have include model , In latest version of sequlize ,
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
include : [
{ model : someModel }
]
raw : true , // <----------- Magic is here
nest : true // <----------- Magic is here
}).success(function (sensors) {
console.log(sensors);
});
you can use the query options {raw: true}
to return the raw result. Your query should like follows:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
})
also if you have associations with include
that gets flattened. So, we can use another parameter nest:true
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
nest: true,
})
For those coming across this question more recently, .values
is deprecated as of Sequelize 3.0.0. Use .get()
instead to get the plain javascript object. So the above code would change to:
var nodedata = node.get({ plain: true });
Sequelize docs here
If I get you right, you want to add the sensors
collection to the node
. If you have a mapping between both models you can either use the include
functionality explained here or the values
getter defined on every instance. You can find the docs for that here.
The latter can be used like this:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
}
}).success(function (sensors) {
var nodedata = node.values;
nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
// or
nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });
nodesensors.push(nodedata);
response.json(nodesensors);
});
There is chance that nodedata.sensors = sensors
could work as well.