我使用nodejs native mongodb client运行以下命令:
db.collection("users").findAndModify(
{ _id:ObjectID.createFromHexString(id), "profiles._id":pid}, {},
{ '$addToSet' : {'profiles.$.categories': category}}, {new:true},
function(err, user){
if(err){
res.json(err);
}
}
);
我有一个我要添加到类别集的类别,问题是在运行后我在集合中看到一个新类别,但属于该类别的一个items数组被设置为null并且未保存。 意味着类别如下:
{
name:'n1',
items:['it1', it2']
}
完整文档如下:
{
_id: ...
profiles: [
{
_id: ...
categories: [
{
name:'c1',
items:['it1', it2']
},
{
name:'c2',
items:['it3', it4']
}
]
}
]
}
答案 0 :(得分:0)
这对我在Mongo shell中的预期效果如下:
> var id = ObjectId(), pid = ObjectId();
> db.users.insert({
... _id: id,
... profiles: [
... {
... _id: pid,
... categories: [
... {
... name: 'c1',
... items: ['it1', 'it2']
... },
... {
... name: 'c2',
... items: ['it3', 'it4']
... }
... ]
...
... }
... ]
... });
>
> var category = {
... name:'n1',
... items:['it1', 'it2']
... };
>
>
> db.users.findAndModify({
... query: { _id: id, "profiles._id": pid},
... update: {
... '$addToSet' : {'profiles.$.categories': category}
... },
... new:true
... });
{
"_id" : ObjectId("51bfc532c0a62b206198663e"),
"profiles" : [
{
"_id" : ObjectId("51bfc532c0a62b206198663f"),
"categories" : [
{
"name" : "c1",
"items" : [
"it1",
"it2"
]
},
{
"name" : "c2",
"items" : [
"it3",
"it4"
]
},
{
"name" : "n1",
"items" : [
"it1",
"it2"
]
}
]
}
]
}