如何更新嵌入式文档 Mongoose 数组中的多个字段?
How can I update multiple fields in an array of embedded documents Mongoose?
我的猫鼬模型:
const userSchema = Schema({
firstName: String,
lastName: String,
books: [{title: String, author: String, isbn: Number}]
});
我想为每个 POST 请求添加 a new title & author with a book object
。我目前的方法给我 positional operator did not find the match
错误:
var User = mongoose.model("User", userSchema);
router.post('/submit', (req, res) => {
let update={
'books.$.title' : req.body.title,
'books.$.author' : req.body.author
}
User.findOneAndUpdate({_id:req.body.user_id},{$push: update},{new: true}).exec(function(err, doc) {
if (err){
console.log(err);
return;
}
res.send(doc);
});
});
我希望在我的数据库中提交两个具有不同作者和标题的表单(POST)得到以下结果:
{
_id: 'SomeId'
firstName: 'John',
lastName: 'Cena',
books: [{title: 'a', author:'b' }, {{title: 'c', author:'d' }}]
}
我不关心 post 中的 ISBN,因为它在我们的架构中不是必填字段。由于我的 books
sub-document 一开始是空的,所以我无法在我的代码中正确设置 positional operator ($)
。请帮助我正确编写 findOneAndUpdate
查询!
$push
需要字段名称和值,在您的情况下,字段名称是 book
,值是一个对象 {author, title}
User.findOneAndUpdate({_id:req.user._id}, {$push : { books : { author: "c", title: "d"}}})
我的猫鼬模型:
const userSchema = Schema({
firstName: String,
lastName: String,
books: [{title: String, author: String, isbn: Number}]
});
我想为每个 POST 请求添加 a new title & author with a book object
。我目前的方法给我 positional operator did not find the match
错误:
var User = mongoose.model("User", userSchema);
router.post('/submit', (req, res) => {
let update={
'books.$.title' : req.body.title,
'books.$.author' : req.body.author
}
User.findOneAndUpdate({_id:req.body.user_id},{$push: update},{new: true}).exec(function(err, doc) {
if (err){
console.log(err);
return;
}
res.send(doc);
});
});
我希望在我的数据库中提交两个具有不同作者和标题的表单(POST)得到以下结果:
{
_id: 'SomeId'
firstName: 'John',
lastName: 'Cena',
books: [{title: 'a', author:'b' }, {{title: 'c', author:'d' }}]
}
我不关心 post 中的 ISBN,因为它在我们的架构中不是必填字段。由于我的 books
sub-document 一开始是空的,所以我无法在我的代码中正确设置 positional operator ($)
。请帮助我正确编写 findOneAndUpdate
查询!
$push
需要字段名称和值,在您的情况下,字段名称是 book
,值是一个对象 {author, title}
User.findOneAndUpdate({_id:req.user._id}, {$push : { books : { author: "c", title: "d"}}})