1

I try to update a MongoDB collection with Mongoose & NodeJS but I have the following error who appears sometimes, but not all the times :

MongoServerError: Plan executor error during findAndModify :: caused by :: The positional operator did not find the match needed from the query.

Here is my code:

NodeJS

try {
  this.myArrayUpdate = { 'description': 'test' };

  this.update = { $set: 
    { 'myArray.$': this.myArrayUpdate }
  };

  const cardId = ObjectId("61d6e320520fac65775a7ba8")

  const userId = ObjectId("61a8e433648e1963ae7358be");

  const filter = { 
    userId: userId,
    'myArray._id': cardId,
  };

  const options = { 
    upsert: true, 
    new: true 
  };

  MyCollection
    .findOneAndUpdate( 
      filter, 
      this.update,
      options,
    )
  .then ( () => {
    return res.status(204).json({ message: 'MyCollection updated ' });
  });
} catch (error) {
  throw error;
}

Mongodb

{
    "_id" : ObjectId("61a8e433648e1963ae7358be"),
    "myArray" : [ 
        {
            "description" : "test",
            "starting" : null,
            "ending" : null,
            "_id" : ObjectId("61d6e320520fac65775a7ba8")
        },
        {
            "description" : "test 2",
            "starting" : null,
            "ending" : null,
            "_id" : ObjectId("61d6e320520fac657812991a")
        },
    ],
}

If found a part of an answer, each time I update my subdocument array, the _id change so it's why there is an error, if I update my page no more error !

Is there a possibility to not create a new _id when updating a subdocument array ?

Thanks for your answer,

David

David
  • 11
  • 4

1 Answers1

0

The document you provided doesn't have an userId field, so your filter won't match the document. The field is called _id:

const filter = { 
    _id: userId,
    'myArray._id': cardId,
  };

Also, the way the update document is written, the entire matched element in myArray will be overwritten, but I assume you only want to update description. It would look like this:

this.update = { $set: 
    { 'myArray.$.description': 'test' }
  };

This is an example of updating a document in an array. Here's a working example in Mongo playground.

Montgomery Watts
  • 3,806
  • 2
  • 10
  • 24
  • Thank you for your answer that's make it work better, but I still have a problem... Is there a possibility to not create a new object _id when updating a subdocument array ? – David Jan 10 '22 at 12:49
  • @David https://stackoverflow.com/questions/17254008/stop-mongoose-from-creating-id-property-for-sub-document-array-items – Montgomery Watts Jan 10 '22 at 18:51