$ elem匹配并更新 [英] $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.
这篇关于$ elem匹配并更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!