Skip to content

Instantly share code, notes, and snippets.

@akilism
Last active August 29, 2015 13:56
Show Gist options
  • Save akilism/9341152 to your computer and use it in GitHub Desktop.
Save akilism/9341152 to your computer and use it in GitHub Desktop.
Node, Q, MongoDB - Upsert an array of objects with a write concern using Q.
var saveObjects = function (objects) {
var MongoC = MongoClient;
var mongoConnect = Q.nbind(MongoC.connect, MongoC);
return mongoConnect(dbString).then(function (db) {
var DocumentCollection = db.collection('collection');
var documentCollectionUpsert = Q.nbind(DocumentCollection.update, DocumentCollection);
//Use upsert option.
var options = { 'w' : 1, 'upsert' : true };
var upsertPromises = objects.map(function (obj) {
return documentCollectionUpsert(obj, obj, options);
});
return Q.all(upsertPromises)
.then(function (results) {
//check results
//...
})
.finally(function () {
db.close();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment