2012-06-21 95 views
0

所以我有一个包含项目数组的播放列表文档。现在我想添加一个投票数组到项目,但我不知道如何做到这一点。目前,这是我怎么添加新项...如何更新MongoDB + Node.js中的嵌套数组

playlist_collection.update(
    {"PlaylistName": playlistName}, 
    {"$push": {items: newitem}}, 
    function(error, playlist){ 
    if(error) callback(error); 
    }); 

我知道有这个几个职位,如果有一个很好的例子重复的罚款。

这里是在db

{ "PlaylistName" : "MyFirstPlaylist", 
    "_id" : ObjectId("4fe0c6570fb2321b39000001"), 
    "comments" : [ ], 
    "created_at" : ISODate("2012-06-19T18:35:03.462Z"), 
    "items" : [ 
     {  "SongName" : "Test", "Location" : "/tmp/40dd4f78466c3c7171f1eaf448e8f1d6" } 
    ] 
} 

回答

0

我结束了使用此对象....

PlaylistProvider.prototype.addVoteToItem = function(, itemname, vote, callback) { 
    this.getCollection(function(error, collection) { 
    collection.findOne({'PlaylistName':playlistName}, function (err, playlist) { 
     if(err) callback(err); 
     playlist.items.forEach(function (item) { 
     for (var prop in item) { 
      if (prop == 'SongName'){ 
      if(item[prop] == itemname){ 
       console.log("Found "+item[prop]) 
       if(item.votes === undefined) item.votes = []; 
      item.votes.push(vote) 
       collection.save(playlist) 
       callback(null, playlist) 
       break; 
      } 
      } 
     } 
     }) 
    }) 
    }) 
}