0

我正在使用 nodejs 本机 mongodb 客户端运行以下命令:

  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);
       } 
    }
  );

我有一个要添加到类别集中的类别,问题是运行后我在集中看到一个新类别,但属于该类别的项目数组设置为 null 并且未保存。意味着一个类别看起来像这样:

{
   name:'n1',
   items:['it1', it2']
}

完整的文档如下所示:

{
  _id: ...      
  profiles: [
    {
      _id: ...
      categories: [
        {
           name:'c1',
           items:['it1', it2']
        },
        {
           name:'c2',
           items:['it3', it4']
        }            
      ]

    }
  ]
}
4

1 回答 1

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"
                    ]
                }
            ]
        }
    ]
}
于 2013-06-18T02:27:10.833 回答