From a78512f16b39422160756fe91ef4d4a3239f5890 Mon Sep 17 00:00:00 2001 From: Ricky Boyce Date: Tue, 14 Jun 2022 10:40:02 +1200 Subject: [PATCH] fix: add _id to upserted document --- lib/model-crud.js | 6 +++++- test/crud.js | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/model-crud.js b/lib/model-crud.js index 1016b82..768af8a 100644 --- a/lib/model-crud.js +++ b/lib/model-crud.js @@ -255,7 +255,11 @@ module.exports = { // Update let update = await this['_' + type](opts.query, operators, util.omit(opts, this._queryOptions)) if (type == 'findOneAndUpdate') response = update - else if (update.n) response = Object.assign(Object.create({ _output: update }), operators['$set']||{}) + else if (update.n) response = Object.assign( + Object.create({ _output: update }), + operators['$set'] || {}, + (update.upserted||[])[0] ? { _id: update.upserted[0]._id } : {}, + ) // Hook: afterUpdate (doesn't have access to validated data) if (response) await util.runSeries(this.afterUpdate.map(f => f.bind(opts, response))) diff --git a/test/crud.js b/test/crud.js index fd90e00..9e6b8a2 100644 --- a/test/crud.js +++ b/test/crud.js @@ -201,6 +201,15 @@ module.exports = function(monastery, opendb) { name: 'Martin Luther3' } ]) + + // Upsert + let newId = db.id() + await expect(user.update({ query: newId, data: { name: 'Martin Luther3' }, upsert: true })) + .resolves.toEqual({ _id: newId, name: 'Martin Luther3' }) // inserted + + await expect(user.update({ query: inserted._id, data: { name: 'Martin Luther4' }, upsert: true })) + .resolves.toEqual({ name: 'Martin Luther4' }) // updated + db.close() })