I am trying to setup a findOneAndUpdate operation that will update a document if it matches 2 filters:
const existingUser = await this.userModel.findOneAndUpdate({id: id, accountId: acc._id},{$set: {name, properties}}, { new: true});
But Mongo is behaving very weirdly. In the example above, there is no document that matches the filters, so none should be returned, correct?
For some weird reason, it returns a document that matched the id
condition. Even though that specific document does not have a accountId
property.
This is the only document I have in the DB:
{
"_id": "62987cceb0b3b13477efa888",
"id": "7",
"name": "Some Name",
"properties": {
"age": "39"
},
"__v": 0
}
When I set moongoose debug to true, I see this in the logs:
Mongoose: users.findOneAndUpdate({ id: '7' }, { '$set': { name: 'Luis Novo', properties: Map(1) { 'age' => '39' } } }, { upsert: false, remove: false, projection: {}, returnDocument: 'after', returnOriginal: false})
For some reason, it is not sending the second parameter.
What am I doing wrong?
CodePudding user response:
Looking at the debug logs, mongoose isn't sending the accountId
in your filter.
Make sure you have accountId
added to your schema, or set strictQuery
to false
to tell mongoose to send fields that do not exist on your schema.
CodePudding user response:
Found the issue. My Model did not contain the field name "accountId". Upon adding the field, it fixed the problem.