Node.js updateOne$set函数赢得';不要在猫鼬里工作
我试图更新数组中的子文档Node.js updateOne$set函数赢得';不要在猫鼬里工作,node.js,express,mongoose,Node.js,Express,Mongoose,我试图更新数组中的子文档books,但没有成功。新数据将无法保存 快递: router.put("/:id/:bookid", (req, res) => { Library.updateOne( { _id: req.params.id, "books._id": req.params.bookid }, { $set: { "books.$.title": "New value" } }
books
,但没有成功。新数据将无法保存
快递:
router.put("/:id/:bookid", (req, res) => {
Library.updateOne(
{ _id: req.params.id, "books._id": req.params.bookid },
{ $set: { "books.$.title": "New value" } }
);
});
图书馆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
}
}
]
});
我做错了什么
编辑:
图书馆表格:
{
"_id": {
"$oid": "12345"
},
"Name": "A random libary",
"Books": [{
"_id": {
"$oid": "1"
}
"title": "TitleExample",
"Chapters": [{
chapterTitle: "first chapter etc"
}]
},
{
"_id": {
"$oid": "2"
}
"title": "Another book" ,
"Chapters": [{
chapterTitle: "first chapter etc"
}]
}]
}
您可以尝试以下方法:
router.put("/:id/:bookid", (req, res) => {
Library.findOne({ _id: req.params.id, "books._id": req.params.bookid }).exec(function(err,result) {
if (err) throw err;
if (result) {
result.books.title = "new value";
result.save()
console.log("new value")
} else {
console.log("not found")
}
});
});
你能用你试图更新的文档和
req.params.id
和req.params.bookid
的值更新你的问题吗?可能是@johnyhk更新的答案与文档重复,选中“编辑”你实际上没有执行更新;查看链接的副本。@johnyhk应该添加.exec()代码>足够了吗?仍然有问题。检查终端时没有错误。或者我必须添加一些东西来检查是否有错误?不起作用,我认为问题在于标题仍然是数组。我检查了console.log(result.books)代码>,并且标题位于结果之后的数组中。书籍
,这会使目标无法访问吗?当我使用result.books.title
时,我得到了undefined
错误。你明白我的意思吗?我在你的方案中看不到的$oid可以通过以下方式更改图书标题:result.books=[{title:'newvalue'}]代码>,但该数组中的所有其他内容都将被删除。是这样做的还是我做错了?$oid
是mongoose在创建新行时自动生成的。我只需要使用\u id
将值与它进行比较。