Hello all,
I have problems updating a subdocument in an array of subdocuments.
Here is my data structure in the users collection:
{
favorites: [
{
id: new ObjectId("639707f36bf9468265d91810"),
expiresAt: 1671361200000,
reminder: false
},
{
id: new ObjectId("637cc4c986b4fbec43579e1f"),
expiresAt: 1672603200000,
reminder: false
}
],
_id: new ObjectId("637e8af40e43f40373686da2"),
email: 'something@something.com',
forename: 'something',
surname: 'something',
role: 'user',
password: 'something',
__v: 0
}
My Schema is:
const userSchema = new Schema({
email: String,
forename: String,
surname: String,
role: String,
password: String,
favorites: {
id: { type: Schema.Types.ObjectId, ref: "Event" },
expiresAt: Number,
reminder: Boolean,
},
});
I want to update the reminder field in a subdocument based on the subdocument’s id.
I’ve tried following approaches:
1. User.findOneAndUpdate(
{ _id: req.body.user, "favorites.id": BSON.ObjectId(req.body.id) },
{ $set: { "favorites.$.reminder": true } },
).setOptions({ sanitizeFilter: true });
Here nothing happens. It finds the document but does not update it.
2. User.findOneAndUpdate(
{ _id: req.body.user },
{ $set: { "favorites.$[elem].reminder": true } },
{
arrayFilters: [{ "elem.id": { $eq: BSON.ObjectId(req.body.id) } }],
returnNewDocument: true,
}
).setOptions({ sanitizeFilter: true });
Here it returns an error: “Error: Could not find path “favorites.0.id” in schema”
I cannot find where is my mistake? Any help is much appreciated!
P.S.
Mongo version is 5.0.14