2016-09-10 82 views
1

我正在使用$in$addToSet來更新我的集合中的數組。假設我有這種文件。

{ 
    _id: objectId(1), //this is just an example id 
    names: ['harry', 'hermione'] 
}, 
{ 
    _id: objectId(2), 
    names: ['ron'] 
}, 
{ 
    _id: objectId(3), 
    names: ['dumbledoor'] 
} 

我要更新所有這些文件,所以我有ID

var arr_ids = [1, 2]; 

的數組,並使用數組map這樣。

var ids = arr_ids.map(function(id) { return mongoose.Types.ObjectId(id); }); 

更新我的集合中的所有文檔。

db.update({ _id: { $in: ids } }, { $addToSet: { name : 'draco' } }, 
    function(err, results) { 
     if(err) console.log(err); 
     console.log(results); 
    } 
); 

我使用$in$addToSet和它的工作原理,並更新文件,但它僅更新的最後文件。

{ 
    _id: objectId(1), //this is just an example id 
    names: ['harry', 'hermione'] 
}, 
{ 
    _id: objectId(2), 
    names: ['ron', 'draco'] // it only update this document. 
}, 
{ 
    _id: objectId(3), 
    names: ['dumbledoor'] 
} 

我不知道爲什麼。我不想創建for循環來單獨更新它,但在我看來,這是我的最後一招。請幫助我。謝謝!

回答