Javascript MongoDb';s$(更新)不更新数组';而是替换它?
我想更新mongodb文档中的数组元素(我使用的是mongoose)。模式类似于:Javascript MongoDb';s$(更新)不更新数组';而是替换它?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我想更新mongodb文档中的数组元素(我使用的是mongoose)。模式类似于: { .. arr : [{ foo: Number, bar: [String], name: String }] .. } 我的问题是: SomeModel.update({ _id: "id of the document", arr: { $elemMatch: { _id: "_id assigned by mongoose to array element" }
{
..
arr : [{
foo: Number,
bar: [String],
name: String
}]
..
}
我的问题是:
SomeModel.update({
_id: "id of the document",
arr: {
$elemMatch: {
_id: "_id assigned by mongoose to array element"
}
}
}, {
'arr.$': {
name: 'new name'
}
}).exec()
它只是替换整个数组元素,例如:
{
_id: "some objectId",
name: 'old name',
foo: 0,
}
致:
我想要的是:
{
_id: "some objectId",
name: 'new name',
foo: 0,
}
我想知道的是,是否有可能在单个更新查询中实现这一点?(我的问题中可能有一个愚蠢的错误:P或其他方法)
我还想这样做更新查询:
{
$inc: { foo: 1},
$push: { bar: "abc"}
}
如果您仍在整个实施过程中苦苦挣扎,您的声明的完整应用如下:
SomeModel.update(
{
"arr._id": "123"
},
{
"$set": { "arr.$.name": "new name" },
"$inc": { "arr.$.foo": 1},
"$push": { "arr.$.bar": "abc" }
}
)
,function(err,numAffected) {
});
因此,每个操作都是依次执行的。可能的重复也作为参考,数组中的
\u id
值不是由MongoDB生成的,而是由Mongoose设置的。MongoDB本身仅为顶级文档分配唯一的\u id
值。可以在mongoose中禁用该行为,但它是当前默认行为。是的,我的坏消息将mongodb更改为mongoose
SomeModel.update(
{
"arr._id": "123"
},
{
"$set": { "arr.$.name": "new name" },
"$inc": { "arr.$.foo": 1},
"$push": { "arr.$.bar": "abc" }
}
)
,function(err,numAffected) {
});