Node.js 水线:访问模型中填充的值
我正在使用开发我的第一个应用程序。我有一个如下所示的模型Node.js 水线:访问模型中填充的值,node.js,orm,sails.js,waterline,Node.js,Orm,Sails.js,Waterline,我正在使用开发我的第一个应用程序。我有一个如下所示的模型 //ModelA.js module.exports = { attributes: { //more attributes userId: { model: 'user' }, //more attributes } }; ModelA.find(options) .populate('us
//ModelA.js
module.exports = {
attributes: {
//more attributes
userId: {
model: 'user'
},
//more attributes
}
};
ModelA.find(options)
.populate('userId')
.exec(function (err, modelA) {
//some logic
//modelA.userId is undefined here
res.json(modelA); //userId is populated in the JSON output
});
我正在我的一个控制器中使用该模型,如下所示
//ModelA.js
module.exports = {
attributes: {
//more attributes
userId: {
model: 'user'
},
//more attributes
}
};
ModelA.find(options)
.populate('userId')
.exec(function (err, modelA) {
//some logic
//modelA.userId is undefined here
res.json(modelA); //userId is populated in the JSON output
});
如何访问模型内填充的值?
ModelA.find
返回项目数组
ModelA.find(options)
.populate('userId')
.exec(function (err, results) {
console.log(results[0].userId) //results is an array.
//res.json(modelA);
});
或者您可以对单个记录使用
ModelA.findOne
,因为find返回一个记录数组。您必须使用索引来访问对象,然后使用该对象的用户ID
ModelA.find(options).populate('userId').exec(function (err, recordsOfModelA) {
if(err) console.log(err);
else console.log(recordsOfModelA[0].userId)
});
只有当它是一对一的关联时,这才有效。在我的例子中,这是一对多的关联。如果是一对多,为什么这不起作用?我看不出有什么理由不起作用。