From 244009923f8553dfa21e918bfebc81032931fd61 Mon Sep 17 00:00:00 2001 From: Nikita Lutsenko Date: Wed, 2 Mar 2016 00:04:14 -0800 Subject: [PATCH] Add findOneAndUpdate to MongoCollection. --- src/Adapters/Storage/Mongo/MongoCollection.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Adapters/Storage/Mongo/MongoCollection.js b/src/Adapters/Storage/Mongo/MongoCollection.js index cabd6038..66113c3d 100644 --- a/src/Adapters/Storage/Mongo/MongoCollection.js +++ b/src/Adapters/Storage/Mongo/MongoCollection.js @@ -46,7 +46,19 @@ export default class MongoCollection { count(query, { skip, limit, sort } = {}) { return this._mongoCollection.count(query, { skip, limit, sort }); } - + + // Atomically finds and updates an object based on query. + // The result is the promise with an object that was in the database !AFTER! changes. + // Postgres Note: Translates directly to `UPDATE * SET * ... RETURNING *`, which will return data after the change is done. + findOneAndUpdate(query, update) { + // arguments: query, sort, update, options(optional) + // Setting `new` option to true makes it return the after document, not the before one. + return this._mongoCollection.findAndModify(query, [], update, { new: true }).then(document => { + // Value is the object where mongo returns multiple fields. + return document.value; + }) + } + // Atomically find and delete an object based on query. // The result is the promise with an object that was in the database before deleting. // Postgres Note: Translates directly to `DELETE * FROM ... RETURNING *`, which will return data after delete is done.