From df39ceac6243492d795a6f70d9fa5ec6110a3aa7 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Mon, 7 Nov 2016 18:54:59 +0000 Subject: [PATCH] fix: Ensure that update returns the correct answer for single updates When { multi: false } is provided, it should return the correct indicator for when a document is updated or not. --- lib/Model.ts | 23 +++++++++++------------ test/Model.ts | 1 + 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/Model.ts b/lib/Model.ts index 9bb1edf..26e55bd 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -560,21 +560,20 @@ export class Model { conditions = this._helpers.convertToDB(conditions); return new Bluebird((resolve, reject) => { - if (opts.multi) - return this.collection.updateMany(conditions, changes, opts, (err, response) => { - if (err) return reject(err); + const callback = (err: Error, response: MongoDB.UpdateWriteOpResult) => { + if (err) return reject(err); - // New MongoDB 2.6+ response type - if (response.result && response.result.nModified !== undefined) return resolve(response.result.nModified); + // New MongoDB 2.6+ response type + if (response.result && response.result.nModified !== undefined) return resolve(response.result.nModified); - // Legacy response type - return resolve(response.result.n); - }); + // Legacy response type + return resolve(response.result.n); + } + + if (opts.multi) + return this.collection.updateMany(conditions, changes, opts, callback); - return this.collection.update(conditions, changes, opts, (err, response) => { - if (err) return reject(err); - return resolve(1); - }) + return this.collection.updateOne(conditions, changes, opts, callback) }) }).nodeify(callback); } diff --git a/test/Model.ts b/test/Model.ts index 0bdeb25..89ca678 100644 --- a/test/Model.ts +++ b/test/Model.ts @@ -804,6 +804,7 @@ describe("Model",() => { it("should allow replacement updates to be conducted",() => { return model.get().then(instance => { + instance.answer++; return chai.expect(model.update(instance._id, instance.document, { multi: false })).to.eventually.equal(1); }); });