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

[Bug] Model.bulkWrite wipes all the document data if no update provided #8331

Closed
AbdelrahmanHafez opened this issue Nov 13, 2019 · 0 comments

Comments

@AbdelrahmanHafez
Copy link
Collaborator

If we for some reason (mostly by mistake) did not provide an update object in updateOne or updateMany operation in Model.bulkWrite, it wipes all the data inside the document except for the _id field.

Here's a test reproducing the issue.

const mongoose = require('./index');
const { Schema } = mongoose;
const assert = require('assert');

const userSchema = new Schema({ name: { type: String, required: true } });

const User = mongoose.model('User', userSchema);

const user = new User({ name: 'Hafez' });

mongoose.connect('mongodb://127.0.0.1:27017/test');
async function run () {
  let threw = false;

  await User.deleteMany();

  await user.save();

  try {
    await User.bulkWrite([{ updateOne: { filter: { _id: user._id } } }]);
  }
  catch (error) {
    threw = true;
  }
  finally {
    assert.equal(threw, true, 'Not providing an update object inside bulk write should throw an error');

    const user = await User.findOne();
    assert.equal(user.name, 'Hafez', 'User data should not be wiped if did not provide an update object.');
  }

}


run().catch(console.error);

What is the expected behavior?

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

This usually happens when a developer is inserting an update object off by one curly brace, which is fairly easy to miss:

User.bulkWrite([{ updateOne: { filter: { _id: user._id } }, update:{ name: 'Sam' } }])

The expected behavior: for bulkWrite to throw an error instead of just wiping all the data inside the documents .

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

No branches or pull requests

1 participant