$elemM 匹配和更新 [英] $elemMatch and update
问题描述
我想更新使用 $elemMatch 获取的子文档.我在网上找到了一些帖子,但到目前为止我无法让它工作.这就是我所拥有的:
I would like to update a subdocument that was fetched using $elemMatch. I've found some posts online but so far I am not able to get it to work. This is what I have:
架构:
var user = {
_id: ObjectId
addresses: [{
_id: ObjectId
street: String
}]
};
代码:
this.findOne({
'addresses._id': address_id
}, { 'occurrences': { $elemMatch: {
'_id': address_id
}}})
.exec(function(err, doc) {
if (doc) {
// Update the sub doc
doc.addresses[0].street = 'Blah';
doc.update({ 'addresses': { $elemMatch: { '_id': address_id }}}, { $set: {"addresses.$.street": doc.addresses[0].street }})
.exec(function(err, count) {
...
上述结果导致地址子文档被清除并重新创建一个空白的新文档.如何保存文档/子文档?
The above results in the address sub doc to be wiped out and a blank new one recreated. How can I save the doc/subdoc?
我的目标是能够通过子文档(地址)ID 获取文档(用户),修改一个匹配的地址然后保存它.
My goal is to be able to fetch a document (user) by subdocument (addresses) ID, modify that one matching address then save it.
推荐答案
您可以通过对模型的单个 update
调用来完成这一切,而不是首先使用 findOne
获取它>:
You can do this all with a single update
call on the model instead of fetching it first with findOne
:
User.update(
{'addresses._id': address_id},
{$set: {'addresses.$.street': 'Blah'}},
function(err, count) { ... });
这使用位置$
$set 中的 > 运算符 只针对查询中匹配的 addresses
元素.
This uses the positional $
operator in the $set
to target just the addresses
element that was matched in the query.
这篇关于$elemM 匹配和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!