2013-11-04 30 views
0

我想将元素添加到找到的元素的数组字段中(如果它尚不存在)。如何在ExpressJS + MongoDB中执行它?expressJS + MongoDB更新 - 将元素添加到数组字段(如果不存在),

我的文档模式:

{ "name" : "Paul", 
"year" : "2013", 
"artist" : "SomeArtist", 
"moods" : [ "angry", "furious" ], 
"_id" : ObjectId("526fe5676f066d0353000002") } 

我想补充的元素插入情绪数组,如果它不存在。 如何在expressJS中做到这一点?

我已经编码的函数,其允许添加元素到数组:

exports.setMood = function(req, res) { 
var nameWhere = req.body.name; 
var newItem = req.body.mood; 

db.collection('tracks', function(err, collection) { 
    collection.update({ name: nameWhere }, { $push: { moods: newItem } }).toArray(function(err, items) { 
     if (err) return res.send(500, err); 
     res.send("OK"); 
    }); 
}); 

};

回答

0

您可以使用为$addToSet

所以在你的例子:

collection.update({ name: nameWhere }, { $addToSet: { moods: newItem } }).toArray(function(err, items) { 
     if (err) return res.send(500, err); 
     res.send("OK"); 
    }); 
相关问题