diff --git a/lib/clients/mongoclient.js b/lib/clients/mongoclient.js index a73cccd..7973fc8 100644 --- a/lib/clients/mongoclient.js +++ b/lib/clients/mongoclient.js @@ -146,15 +146,25 @@ class MongoClient extends DatabaseClient { // Always return the updated object options.returnOriginal = false; + // If the query is empty, and trying to upsert, just create... + if (options.upsert && Object.keys(query).length === 0) { + delete options.upsert + + return new Promise(function(resolve, reject) { + const db = that._mongo.collection(collection); + + db.insert(values, options, function(error, result) { + if (error) return reject(error); + resolve(result.ops && result.ops.length && result.ops[0]); + }); + }); + } + + // ...otherwise, run the regular findOneAndUpdate return new Promise(function(resolve, reject) { const db = that._mongo.collection(collection); - let update = values; - if (options.upsert) { - update = { $setOnInsert: update }; - } else { - update = { $set: update }; - } + let update = { $set: values }; db.findOneAndUpdate(query, update, options, function(error, result) { if (error) return reject(error); @@ -265,7 +275,7 @@ class MongoClient extends DatabaseClient { options = options || {}; options.unique = options.unique || false; options.sparse = options.sparse || false; - + const db = this._mongo.collection(collection); let keys = {}; @@ -404,4 +414,4 @@ const castQueryIds = function(query) { return query; }; -module.exports = MongoClient; \ No newline at end of file +module.exports = MongoClient; diff --git a/package.json b/package.json index c480b77..5e0af54 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "camo", - "version": "0.12.3", + "version": "0.12.6", "description": "A class-based ES6 ODM for Mongo-like databases.", "author": { "name": "Scott Robinson",