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