Skip to content

Atomic upsertWithWhere #563

New issue

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

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

Already on GitHub? # to your account

Merged
merged 1 commit into from
Nov 30, 2020
Merged
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
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,
};