Modify sub documents after matching parent document and sub document

匿名 (未验证) 提交于 2019-12-03 01:46:01

问题:

I have a scenario that I have a document inside which I have a sub collection. Now, I want to modify/update one of the sub document from the sub collection. I want to match the parent document and the sub document first before modifying the sub document. I am using mongoose/node.js and MongoDB

Here is my schema:-

var mongoose     = require('mongoose'); var Schema       = mongoose.Schema;  var HostSchema   = new Schema({      aid         :       String,     cars        :       [{                                 carid : String,                                 status_code: Number                                          }] });  module.exports = mongoose.model('Host', HostSchema);

Here is my code:-

router.route('/xxx/').post(function(req, res) {      Host.findOne({         _id : req.body.xid     }, {         cars : {             carid : req.body.yid         }      }, function(err, host) {         if (err) {             res.send(err);         } else {             // What to do?         }     }); });

I am able to print the whole sub collection but instead I want only one document matched from the sub collection should be printed. My goal is to modify the status_code field in the document of the sub collection

回答1:

My goal is to modify the status_code field in the document of the sub collection

You need to use the $ positional operator to update the sub document that matches the query.

Host.update({"_id":req.body.xid,"cars.carid":req.body.yid},             {$set:{"cars.status_code":50}},function(err,numEffected){             console.log(numEffected); })


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!