对于我的 express/mongo/mongoose 路由器,我试图在发送之前将一个对象附加到另一个对象。不幸的是它从来没有。我哪里错了?
值得注意的是,response_study 是一个对象数组,如果这很重要的话。
response_study 也不为空。
apiRouter.route('/compounds/:_id')
.get(function(req, res) {
Compound.findById(req.params._id, function(err, compound) {
if (err) res.send(err);
Study.find({compound_id: compound._id}, function( err, response_study){
if (err) res.send(err);
compound["studies"] = response_study;
console.log(compound); //logs compound without studies parameter
res.json(compound);
});
});
})
最佳答案
看起来您正在使用 Mongoose?如果是这样,它们不会返回普通对象,而是返回 MongooseDocument
对象。在更改之前,您需要将 MongooseDocument
转换为普通对象,否则您的更改将不会产生任何效果:
var response = compound.toObject();
response.studies = response_study;
res.json(response);
http://mongoosejs.com/docs/api.html#document_Document-toObject
我已经有一段时间没有使用 Mongoose 了,所以它可能是 toJSON
而不是
关于javascript - 为什么我不能将数组作为成员添加到我的对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35347254/