mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Cannot update array of arrays using Document.set

Open BrunoGodefroy opened this issue 6 years ago • 1 comments

Do you want to request a feature or report a bug? Report a bug

What is the current behavior? Setting the content of an array of arrays throws a MongoError: The positional operator did not find the match needed from the query.

Doing exactly the same update with updateOne works fine.

If the current behavior is a bug, please provide the steps to reproduce.

Assuming a connection to a mongo server has been established, the following jest test should demonstrate the issue (I have the same bug outside of the jest environment I just used it for convenience):

describe('Test mongoose', () => {
  const schema = new mongoose.Schema({
    name: String,
    array: [[{
      label: String,
      value: String,
    }]],
  });
  const MyModel = mongoose.model('MyModel', schema);
  const updateQuery = {
    'array.0': [{
      label: 'hello',
      value: 'world',
    }],
  };

  test('It works to update nested array using updateOne', async () => {
    const doc = await new MyModel({ name: 'foo' }).save();
    await MyModel.updateOne({ _id: doc._id }, { $set: updateQuery });

    const updatedDoc = await MyModel.findOne({ _id: doc._id });
    expect(updatedDoc.array[0][0].label).toBe('hello');
    expect(updatedDoc.array[0][0].value).toBe('world');
    // Success!
  });

  test('It works to update nested array using set', async () => {
    const doc = await new MyModel({ name: 'foo' }).save();
    await doc.set(updateQuery).save();  // Fails MongoError: The positional operator did not find the match needed from the query.

    const updatedDoc = await MyModel.findOne({ _id: doc._id });
    expect(updatedDoc.array[0][0].label).toBe('hello');
    expect(updatedDoc.array[0][0].value).toBe('world');
  });
});

After a git bisect I have found the commit that caused the issue: https://github.com/Automattic/mongoose/commit/51c6776a9a67368cd2cb1cf170996912353ee204

Downgrading to 5.7.12 fixes the issue.

What is the expected behavior? Should update the nested array using doc.set

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version. mongoose: 5.7.13 mongoDB: 4.2.0 Node: 10.16.0

BrunoGodefroy avatar Mar 19 '20 15:03 BrunoGodefroy

I can confirm that this is an issue: the following gets sent in the case of MyModel.updateOne(...):

{
  '$set': {
    'array.0': [{
      label: 'hello',
      value: 'world'
    }]
  }
}

using doc.set(updateQuery).save() adds an'array.$': [[undefined]] to the update sent to Mongo:

{
  '$set': {
    'array.$': [
      [undefined]
    ],
    'array.0': [{
      label: 'hello',
      value: 'world'
    }]
  }
}

AbdelrahmanHafez avatar Mar 19 '20 16:03 AbdelrahmanHafez