问题
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);
})
来源:https://stackoverflow.com/questions/27433032/modify-sub-documents-after-matching-parent-document-and-sub-document