Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove $setOnInsert from findOneAndUpdate #100

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions lib/clients/mongoclient.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 = {};
Expand Down Expand Up @@ -404,4 +414,4 @@ const castQueryIds = function(query) {
return query;
};

module.exports = MongoClient;
module.exports = MongoClient;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down