如何解决如何在mongodb中更新数组
我正在尝试更新猫鼬集合中某个项目中的数组。这可能很晦涩,所以这是我的代码。
const itemSchema = new mongoose.Schema({
name: String,});
const listSchema = new mongoose.Schema({
name: String,items: [itemSchema],});
这些是架构
List.findOne({name:listTitle},function (err,list) {
if (err) {
console.log(err);
} else {
list.items.push(item)
res.redirect(`/${listTitle}`)
}
})
这是我要为其更新List集合中的items数组的代码。
它不会显示控制台中的任何错误,但不会更新阵列。
任何建议?
解决方法
您可以直接去:-
它将根据您的条件查找文档,然后对其进行更新。 更新时,您需要使用此$ push运算符将元素推入数组。
List.findOneAndUpdate({name:listTitle},{
$push: {
items: item
}
},function (err,list) {
if (err) {
console.log(err);
} else {
res.redirect(`/${listTitle}`)
}
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。