node.js - 如何使用基于唯一id的节点更新mongodb中的多个文档
问题描述
如何在 mongoose 中更新多个文档,我知道如何更新与其他文档匹配的多个文档,但我希望使用 id 更新多个文档。
我尝试了很多方法,这里是其中之一。
更新
var myid = req.params.noteId
Note.updateMany({ _id:{ $in:ObjectID(myid) } }, {
lname: req.body.lname || "Untitled Note",
age: req.body.age
}, { new: true })
.then(note => {
if (!note) {
return res.status(404).send({
message: "Note not found with id " + req.params.noteId
});
}
res.send(note);
})
还有一件事我如何将多个 Id 作为参数传递以更新邮递员测试仪中的多个文档。
解决方案
mongoose.Types.ObjectId.isValid
将返回布尔值。检查这个https://github.com/mongodb/js-bson/blob/f7efecc04240525931402116f881b5984af800c4/lib/bson/objectid.js#L247
如果您想更新多个 id 以在 req.body 中传递这些 id
多次使用 $in 否则直接通过。
var myid = req.params.noteId;
if (mongoose.Types.ObjectId.isValid(myid)) {
Note.update({
_id: mongoose.Types.ObjectId(myid)
// _id: {$in: req.body.somekey_array.map(id => mongoose.Types.ObjectId(id ))} //multiple
}, {
lname: req.body.lname || "Untitled Note",
age: req.body.age
}, {
multi: true //multiple
})
.then(note => {
console.log('----qqqqq--', note)
if (!note) {
return res.status(404).send({
message: "Note not found with id " + req.params.noteId
});
}
res.json(note);
});
} else {
res.status(400).json({
msg: 'id not correct'
});
}
推荐阅读
- android - 检测用户是否从应用程序上的唯一设备创建帐户
- ios - 运行 UIKit 目录 swift 示例代码时遇到问题
- excel - stata:保存时工作表名称不存在
- java - Tibco 8.6 64 位 RVD 连接问题
- python-3.x - 线性时间的拓扑排序复杂度?
- c - 为了完成这个问题,我应该如何修改函数中的指针算法?
- javascript - 为什么我的隐藏表格在按钮单击时没有显示?
- python - 通过 SQL 查询传递列表时收到“错误:SQL 语句中未使用所有参数”
- html - 在横向模式下使 div 在 Y 中可滚动
- python - 在 django 中管理 helper/utils 函数及其敏感数据