[英]MongoDB How to update the first item that matches a condition in an array of documents?
[英]How to update array of documents in mongodb?
我有如下的AdminGroupOperation模型:
var AdminGroupOperation = new mongoose.Schema({
module : String,
adminGroup: {type: mongoose.Schema.Types.ObjectId, ref: 'AdminGroup'},
operations: [{type: mongoose.Schema.Types.ObjectId, ref: 'Operation'}],
recycled: Number
});
和我的Operation模型如下所示:
var Operation = new mongoose.Schema({
name : String,
value: Boolean,
recycled: Number
});
如何在AdminGroupOperations模型中更新操作数组? 在我的api中,我有类似的内容,但这是行不通的。
exports.update = function (req, res, next) {
var data = req.body;
AdminGroupOperation.findByIdAndUpdate({"_id": req.params.id}, {
module : data.module,
adminGroup: data.adminGroup._id,
operations: data.$.operations_id
},
{new: true},
function (err, secoperation) {
if (err) {
return next(err);
}
secoperation.save(function (err) {
if (err) {
return next(err);
}
});
res.json({'status': 'updated', 'ID': req.params.id});
})
};
您必须在没有请求的情况下使用id,我的意思是:
AdminGroupOperation.findByIdAndUpdate req.params.id, { $set:{
module : data.module,
adminGroup: data.adminGroup._id,
operations: data.$.operations_id
}}, {new: true},
function (err, secoperation) {
if (err) {
return next(err);
}
secoperation.save(function (err) {
if (err) {
return next(err);
}
});
res.json({'status': 'updated', 'ID': req.params.id});
})
};
我不确定该选项:{new:true},或者您可以简单地使用update并通过请求查找ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.