Skip to content

Commit

Permalink
Merge pull request #9097 from AbdelrahmanHafez/gh-9096
Browse files Browse the repository at this point in the history
feat(document): add Document#getChanges
  • Loading branch information
vkarpov15 committed Jun 15, 2020
2 parents 24f6a29 + 6bd202e commit 7cc8823
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
39 changes: 39 additions & 0 deletions lib/document.js
Expand Up @@ -3830,6 +3830,45 @@ Document.prototype.$__fullPath = function(path) {
return path || '';
};

/**
* Returns the changes that happened to the document
* in the format that will be sent to MongoDB.
*
* ###Example:
* const userSchema = new Schema({
* name: String,
* age: Number,
* country: String
* });
* const User = mongoose.model('User', userSchema);
* const user = await User.create({
* name: 'Hafez',
* age: 25,
* country: 'Egypt'
* });
*
* // returns an empty object, no changes happened yet
* user.getChanges(); // { }
*
* user.country = undefined;
* user.age = 26;
*
* user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
*
* await user.save();
*
* user.getChanges(); // { }
*
* @return {Object} changes
*/

Document.prototype.getChanges = function() {
const delta = this.$__delta();

const changes = delta ? delta[1] : {};
return changes;
};

/*!
* Module exports.
*/
Expand Down
25 changes: 25 additions & 0 deletions test/document.test.js
Expand Up @@ -8976,6 +8976,31 @@ describe('document', function() {
assert.equal(axl.fullName, 'Axl Rose');
});

describe('Document#getChanges(...) (gh-9096)', function() {
it('returns an empty object when there are no changes', function() {
return co(function*() {
const User = db.model('User', { name: String, age: Number, country: String });
const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' });

const changes = user.getChanges();
assert.deepEqual(changes, {});
});
});

it('returns only the changed paths', function() {
return co(function*() {
const User = db.model('User', { name: String, age: Number, country: String });
const user = yield User.create({ name: 'Hafez', age: 25, country: 'Egypt' });

user.country = undefined;
user.age = 26;

const changes = user.getChanges();
assert.deepEqual(changes, { $set: { age: 26 }, $unset: { country: 1 } });
});
});
});

it('supports skipping defaults on a document (gh-8271)', function() {
const testSchema = new mongoose.Schema({
testTopLevel: { type: String, default: 'foo' },
Expand Down

0 comments on commit 7cc8823

Please sign in to comment.