Skip to content

Commit

Permalink
pass number of affected docs back on update/save
Browse files Browse the repository at this point in the history
  • Loading branch information
aheckmann committed Feb 8, 2012
1 parent 31a0123 commit fc06a9b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
17 changes: 14 additions & 3 deletions lib/model.js
Expand Up @@ -262,11 +262,22 @@ Model.prototype.init = function init (doc, query, fn) {
};

function handleSave (promise, self) {
return tick(function handleSave (err) {
return tick(function handleSave (err, result) {
if (err) return promise.error(err);

self._storeShard();
self.emit('save', self);
promise.complete(self);

var numAffected;
if (result) {
numAffected = result.length
? result.length
: result;
} else {
numAffected = 0;
}

self.emit('save', self, numAffected);
promise.complete(self, numAffected);
promise = null;
self = null;
});
Expand Down
17 changes: 17 additions & 0 deletions test/model.test.js
Expand Up @@ -4634,5 +4634,22 @@ module.exports = {
});
});
});
},

'number of affected docs should be returned when saving': function () {
var db = start()
var schema = new Schema({ name: String });
var S = db.model('AffectedDocsAreReturned', schema);
var s = new S({ name: 'aaron' });
s.save(function (err, doc, affected) {
should.strictEqual(null, err);
affected.should.equal(1);
s.name = 'heckmanananananana';
s.save(function (err, doc, affected) {
db.close();
should.strictEqual(null, err);
affected.should.equal(1);
});
});
}
};
17 changes: 16 additions & 1 deletion test/model.update.test.js
Expand Up @@ -456,8 +456,9 @@ module.exports = {
s.save(function (err) {
should.strictEqual(null, err);

S.update({ _id: s._id }, { ignore: true }, function (err) {
S.update({ _id: s._id }, { ignore: true }, function (err, affected) {
should.strictEqual(null, err);
affected.should.equal(1);

S.findById(s._id, function (err, doc) {
db.close();
Expand All @@ -467,6 +468,20 @@ module.exports = {
});
});
});
},

'model.update passes number of affected documents': function () {
var db = start()
, B = db.model('BlogPost', 'wwwwowowo'+random())

B.create({ title: 'one'},{title:'two'},{title:'three'}, function (err) {
should.strictEqual(null, err);
B.update({}, { title: 'newtitle' }, { multi: true }, function (err, affected) {
db.close();
should.strictEqual(null, err);
affected.should.equal(3);
});
});
}

}

0 comments on commit fc06a9b

Please sign in to comment.