Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(document): add Document#getChanges #9097

Merged
merged 4 commits into from Jun 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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