Sequelize JS:如何删除结果集中的嵌套对象
Sequelize JS: How to remove nested object in result set
使用 sequelize.js 时,如何指定 returned 对象不包含包含的模型作为嵌套对象。
例如:
Model1.findAll({
include: [{ model: Model2 }]
})
这将 return:
{ id: X, ..., Model2: { ... } }
但我想得到
{ id: X, ..., <model2 attributes> }
如果不修改结果对象,就无法做到这一点。
您有两个选择:
var _ = require("lodash");
Model1
.findAll()
.then( function( instance1 ) {
return instance1
.getModel2()
.then( function( instance2 ) {
return _.extend(instance1.toJSON(), instance2.toJSON() );
});
}).then( function( instance1 ) { console.log(instance1) } );
这将创建两个数据库查询。
您的第二个选择是:
var _ = require("lodash");
Model1
.findAll({
include: [{ model: Model2 }]
})
.then( function( instance1 ) { return instance1.toJSON() } )
.then( function( instance1 ) {
var flatInstance = _.extend(instance1, instance1['Model2']);
delete flatInstance['Model2'];
return flatInstance;
})
.then( function( instance1 ) { console.log(instance1) } );
这将只使用一个查询。
使用 sequelize.js 时,如何指定 returned 对象不包含包含的模型作为嵌套对象。
例如:
Model1.findAll({
include: [{ model: Model2 }]
})
这将 return:
{ id: X, ..., Model2: { ... } }
但我想得到
{ id: X, ..., <model2 attributes> }
如果不修改结果对象,就无法做到这一点。
您有两个选择:
var _ = require("lodash");
Model1
.findAll()
.then( function( instance1 ) {
return instance1
.getModel2()
.then( function( instance2 ) {
return _.extend(instance1.toJSON(), instance2.toJSON() );
});
}).then( function( instance1 ) { console.log(instance1) } );
这将创建两个数据库查询。
您的第二个选择是:
var _ = require("lodash");
Model1
.findAll({
include: [{ model: Model2 }]
})
.then( function( instance1 ) { return instance1.toJSON() } )
.then( function( instance1 ) {
var flatInstance = _.extend(instance1, instance1['Model2']);
delete flatInstance['Model2'];
return flatInstance;
})
.then( function( instance1 ) { console.log(instance1) } );
这将只使用一个查询。