我正在尝试更新一个数组,这是在一个项目在猫鼬的集合。这可能很模糊,所以这里是我的代码。
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}`)
}
})
这是我试图更新列表集合中的items数组的代码。
它不会在控制台中显示任何错误,但也不会更新数组。
有什么建议吗??
你可以直接去:-
Collection.FindOneAndUpdate()
它将根据您的条件找到文档,然后对其进行更新。在更新时,您需要使用$push运算符将元素推送到数组。
List.findOneAndUpdate({name:listTitle}, {
$push: {
items: item
}
}, function (err, list) {
if (err) {
console.log(err);
} else {
res.redirect(`/${listTitle}`)
}
})