Skip to content

Commit

Permalink
fix: add _id to upserted document
Browse files Browse the repository at this point in the history
  • Loading branch information
boycce committed Jun 13, 2022
1 parent b7039ae commit a78512f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/model-crud.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
9 changes: 9 additions & 0 deletions test/crud.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})

Expand Down

0 comments on commit a78512f

Please sign in to comment.