Skip to content

Commit

Permalink
Merge 9dcd1db into 4551cc0
Browse files Browse the repository at this point in the history
  • Loading branch information
mrbatista committed Nov 27, 2020
2 parents 4551cc0 + 9dcd1db commit a73dc3a
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
71 changes: 71 additions & 0 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -1695,6 +1695,77 @@ MongoDB.prototype.update = MongoDB.prototype.updateAll = function updateAll(
);
};

MongoDB.prototype.upsertWithWhere = function upsertWithWhere(
modelName,
where,
data,
options,
cb,
) {
const self = this;

if (self.debug) {
debug('upsertWithWhere', modelName, where, data);
}

let updateData = Object.assign({}, data);

const idValue = self.getIdValue(modelName, updateData);
const idName = self.idName(modelName);

where = self.buildWhere(modelName, where, options);

if (idValue === null || idValue === undefined) {
delete updateData[idName]; // Allow MongoDB to generate the id
} else {
const oid = self.coerceId(modelName, idValue, options); // Is it an Object ID?c
updateData._id = oid; // Set it to _id
if (idName !== '_id') {
delete updateData[idName];
}
}

updateData = self.toDatabase(modelName, updateData);

// Check for other operators and sanitize the data obj
updateData = self.parseUpdateData(modelName, updateData, options);

this.execute(
modelName,
'findOneAndUpdate',
where,
updateData,
{
upsert: true,
returnOriginal: false,
sort: [['_id', 'asc']],
},
function(err, result) {
if (err) return cb && cb(err);

if (self.debug)
debug('upsertWithWhere.callback', modelName, where, updateData, err, result);

const object = result && result.value;
self.setIdValue(modelName, object, object._id);
if (object && idName !== '_id') {
delete object._id;
}

let info;
if (result && result.lastErrorObject) {
info = {isNewInstance: !result.lastErrorObject.updatedExisting};
} else {
debug('upsertWithWhere result format not recognized: %j', result);
}

if (cb) {
cb(err, self.fromDatabase(modelName, object), info);
}
},
);
};

/**
* Disconnect from MongoDB
*/
Expand Down
1 change: 1 addition & 0 deletions test/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ global.connectorCapabilities = {
ilike: false,
nilike: false,
nestedProperty: true,
atomicUpsertWithWhere: true,
};

0 comments on commit a73dc3a

Please sign in to comment.