Node.js 使用mongoose更新嵌套数组中的字段
我正在尝试更新数组中的子文档,但未成功。新数据无法保存 快递:Node.js 使用mongoose更新嵌套数组中的字段,node.js,express,mongoose,Node.js,Express,Mongoose,我正在尝试更新数组中的子文档,但未成功。新数据无法保存 快递: router.put('/:id/:bookid', (req, res) => { library.findOneAndUpdate( { "_id": req.params.id, "books._id": req.params.bookid}, { "$set": { "title.$": 'new title' } } }); 图书馆SCEMA:
router.put('/:id/:bookid', (req, res) => {
library.findOneAndUpdate(
{ "_id": req.params.id, "books._id": req.params.bookid},
{
"$set": {
"title.$": 'new title'
}
}
});
图书馆SCEMA:
const LibarySchema = new Library({
Name: {
type: String,
required: false
},
books: [BookSchema]
});
图书管理局:
const BookSchema = new Schema({
title: {
type: String,
required: false
},
Chapters: [
{
chapterTitle: {
type: String,
required: false
}
}
]
});
我只想更新子文档,而不是同时更新父文档和子文档。我也遇到了类似的问题。我相信$set在嵌套数组方面有问题,GitHub上有一个完整的问题线程。这就是我解决问题的方法
var p = req.params;
var b = req.body;
Account.findById(req.user._id, function (err, acc) {
if (err) {
console.log(err);
} else {
acc.websites.set(req.params._id, req.body.url); //This solved it for me
acc.save((err, webs) => {
if (err) {
console.log(err);
} else {
console.log('all good');
res.redirect('/websites');
}
});
}
});
我有一个嵌套数组的用户
试试这个代码
router.put('/:id/:bookid', (req, res) => {
library.findById(
req.params.id, (err, obj) => {
if (err) console.log(err); // Debugging
obj.books.set(req.params.bookid, {
"title": 'new title',
'Chapters': 'your chapters array'
});
obj.save((err,obj)=>{
if(err) console.log(err); // Debugging
else {
console.log(obj); // See if the saved object is what expected;
res.redirect('...') // Do smth here
}
})
})
});
让我知道它是否有效,我会补充解释
说明:在本例中,首先查找正确的对象库,然后在名为books的数组中找到正确的对象
使用.set可将整个对象设置为新状态。您需要从库对象的上一个实例获取未更改的数据
我相信这种方法将覆盖并删除未传递到.set方法中的任何数据。然后保存更改后的。我对express/mongoose还不熟悉,因此很难理解您的解决方案。你有没有可能编辑这个解决方案,让它与我的案例一起工作?