我在一个集合中有一个 ObjectId 的引用数组。我想返回与 json 响应中的这些 Id 链接的对象数据。
retrieveFromUser: function( req, res ) {
var user_id = req.params.user_id;
User.findById( user_id, function( err, user ) {
if( err ) {
res.send( 404, "Unable to find user");
} else {
// This returns the array but I want the objects data
return res.json( user.constructions );
}
});
}
我该怎么做?
非常感谢!
最佳答案
尝试使用populate()方法
retrieveFromUser: function( req, res ) {
var user_id = req.params.user_id;
User.findOne({ _id: user_id }).populate('constructions').exec(function( err, user ) {
if( err ) {
res.send( 404, "Unable to find user");
} else {
// This returns the array but I want the objects data
return res.json( user.constructions );
}
});
}
关于javascript - NodeJS 和 MongoDB - ObjectId 数组如何返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19290585/