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

Improve handling of defaults when using pull() #12419

Merged
merged 3 commits into from Sep 12, 2022
Merged

Conversation

vkarpov15
Copy link
Collaborator

Summary

The problem here is that pull() adds defaults to the query filter that is sent to MongoDB on save(), so it won't match documents that don't have the default set. This behavior is problematic because this may cause save() to start not pulling documents if the user adds a new property with a default to the schema.

We fix this by explicitly removing any fields that are set to default in the document.

const catschema = new Schema({
  name: String,
  colors: [{
    _id: false,
    hex: { type: String, default: '#ffffff' },
    name: String
  }]
});
const Cat = db.model('Test', catschema);

const cat = new Cat({});
cat.init({
  name: 'Garfield',
  colors: [{ name: 'Orange' }]
});

cat.colors.pull({ name: 'Orange' });
// Sends `{ $pull: { colors: { $or: [{ name: 'Orange', hex: '#ffffff' }] } } }
await cat.save();

Examples

Copy link
Collaborator

@AbdelrahmanHafez AbdelrahmanHafez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks 👍

@vkarpov15 vkarpov15 merged commit 97c3bdb into master Sep 12, 2022
@vkarpov15 vkarpov15 deleted the vkarpov15/gh-12294 branch September 12, 2022 01:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants