javascript - 为什么我不能将数组作为成员添加到我的对象中

标签 javascript node.js mongodb mongoose

对于我的 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/

相关文章:

javascript - 避免 "Cannot read property ' addEventListener' of null 的最佳方法”

javascript - 替换 for 循环中的 id 属性

javascript - 从 tween.js 中提取补间值

javascript - 如何在 HTML 文件中包含 npm 包?

javascript - MongoDB 嵌套对象的聚合过滤

javascript - 使按钮在按下 Enter 时单击

node.js - 亚马逊 EC2 Ubuntu 实例 : Where should I upload the files to access them from the browser?

CSS 在 a2hosting 上使用 node.js 抛出 503 错误

asp.net - 使用 MongoDB 和 ASP.NET MVC 进行分页的高效方式

mongodb - 无法从 GCP App Engine 连接到 Mongo Atlas