I have problem updating a subdocument in an array of subdocuments

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

Hello @Kaloyan_Hristov,

It causing the issue because the type of the favorites property is an object in your schema, and your example document has that in the array of objects,

So if it is an array of objects then you need to change you schema like this,

const userSchema = new Schema({
  email: String,
  forename: String,
  surname: String,
  role: String,
  password: String,
  favorites: [
    {
      _id: false,
      id: { type: Schema.Types.ObjectId, ref: "Event" },
      expiresAt: Number,
      reminder: Boolean,
    }
  ]
});

After changes in schema, try your query I think it should work.

2 Likes

Hi,

Amazing how stupid I am :smiley:

That was the problem.

Thank you very much!!!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.