使用mongodb更新复杂对象

时间:2015-04-27 14:58:37

标签: node.js mongodb

我有一个像这样结构的Json对象。

/* 1 */
{
    "_id" : ObjectId("553e4b0a903fd38019ac2a6a"),
    "id" : 19,
    "monday" : {
        "entrees" : [],
        "viandes" : [],
        "legumes" : [],
        "fromages" : [],
        "desserts" : []
    },
    "thursday" : {
        "entrees" : [],
        "viandes" : [],
        "legumes" : [],
        "fromages" : [],
        "desserts" : []
    },
    "wednesday" : {
        "entrees" : [],
        "viandes" : [],
        "legumes" : [],
        "fromages" : [],
        "desserts" : []
    },
    "tuesday" : {
        "entrees" : [],
        "viandes" : [],
        "legumes" : [],
        "fromages" : [],
        "desserts" : []
    },
    "friday" : {
        "entrees" : [],
        "viandes" : [],
        "legumes" : [],
        "fromages" : [],
        "desserts" : []
    }
}

我想更新此对象,在数组中插入值。

我测试了不同的查询,但我的对象永远不会更新。

例如,此查询无法正常工作。

self.menucollection.update(
{
    'id' : id
},
{
    $set:{ 'monday':{
        'entrees' : 'toot'
        }
    }   
},
function(err, item){
    callback(err, item);
}
);

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

要添加到数组,您必须使用$push

此外,使用dot notation访问星期一/主菜。

self.menucollection.update({'id': id}, { $push: { 'monday.entrees': 'toot'  }});