通过Mongoose更新和/或添加使用req.body的数组元素属性? [英] Update and/or add array element properties using req.body via Mongoose?
本文介绍了通过Mongoose更新和/或添加使用req.body的数组元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下文件:
{
"_id" : ObjectId("503b83dfad79cc8d26000004"),
"pdfs" : [
{
"title" : "Test document",
"pdf_id" : ObjectId("504f6793ce351a595d000004"),
"created_at" : ISODate("2012-09-11T16:32:19.276Z")
},
{
"title" : "Some other doc",
"pdf_id" : ObjectId("502bf124b4642341230003f0"),
"created_at" : ISODate("2012-09-11T11:34:19.276Z")
}
]
}
现在,通过 req.body
的传入表单,我有2个字段: code> title 和 description
。
Now in an incoming form via req.body
, I have 2 fields: title
and description
.
我想更新标题
并插入描述
一个指定的pdf_id,我该怎么做?
I want to update title
and insert description
for a specified pdf_id, how do I do that?
所以最后,我的文档现在看起来像:
So in the end, my document will now look like:
{
"_id" : ObjectId("503b83dfad79cc8d26000004"),
"pdfs" : [
{
"title" : "This is an UPDATED title",
"description" : "It has an ALL NEW description",
"pdf_id" : ObjectId("504f6793ce351a595d000004"),
"created_at" : ISODate("2012-09-11T16:32:19.276Z")
},
{
"title" : "Some other doc",
"pdf_id" : ObjectId("502bf124b4642341230003f0"),
"created_at" : ISODate("2012-09-11T11:34:19.276Z")
}
]
}
要清楚,我只是在寻找Mongoose 更新
语法。 / p>
Just to be clear, I'm really just looking for the Mongoose update
syntax.
推荐答案
你可以e $
位置操作符,参考 $ set
中匹配的 pdfs
数组元素:
You can use the $
positional operator to refer to the matched pdfs
array element in your $set
:
Model.update(
{ 'pdfs.pdf_id': pdf_id },
{ $set: {
'pdfs.$.title': title,
'pdfs.$.description': description
}}, function (err, numAffected) { ... }
);
这篇关于通过Mongoose更新和/或添加使用req.body的数组元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文