mercredi 1 avril 2015

Mongoose add filter to insert in node.js

I have a array of data need to be inserted to mongodb. But the array has some data have already existed in mongodb. How to insert this array of data only the parts which not existed in mongodb. The struct is like below: [ { "_id" : ObjectId("551ca2b973d1124a0445f491"), "url" : "http://ift.tt/1DqytOP", "createdAt" : ISODate("2015-04-02T02:00:25.395Z"), }, { "_id" : ObjectId("551ca2b973d1124a0445f492"), "url" : "http://ift.tt/1DqytOR", "createdAt" : ISODate("2015-04-02T02:00:25.401Z"), "__v" : 0 } ]


For example the first document's url has already existed in mongodb, how to add a filter or exclude it from the array and then insert it into the mongodb.


My current insert code like below:


var imgDicts = []; for (var i = 0; i < imgs.length; i++) { var img = imgs[i].img; var imgDict = {url: img, createdAt: Date.now()}; imgDicts.push(imgDict); }; console.log(imgDicts); Img.collection.insert(imgDicts, function(err, docs){ if (err) { callback(err, null); } else { callback(null, {message: 'success'}); } });


Aucun commentaire:

Enregistrer un commentaire