Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

Update nested array of Objects in Mongoose


I need to update the 'categories' array located in the 'menu'(model) schema. I would like to change the name of a specific Category.

The 'category' schema is just a schema - not a model... this code is in a nosejs server

Here are my Schemas :

   const menuSchema = new mongoose.Schema(
  {
    user: {
      type: ObjectId,
      ref: "User",
      required: true,
    },
    restName: {
      type: String,
      trim: true,
      required: true,
    },
    categories: [categorySchema],
  },
  {
    timestamps: true,
  }
)

The 'category' Schema:

  const categorySchema = new mongoose.Schema(
  {

    name: {
      type: String,
      required: true,
    },

  {
    timestamps: true,
  }
)

I try to do this :

try {
let updateMenu = await Menu.updateOne(
  { _id: menuId, "categories.$.name": oldCatName },
  { $set: { "categories.$.name": newName } }
)

Just can't understand this in mongoose

Please help


Solution

  • In your menuSchema "categories" shoud be an array of objectId refer to other schema like

    categories = [productId: {
                  type: mongoose.Schema.Types.ObjectId,
                  ref: 'categorySchema',}
                 ]
    

    and afterthat populate categories where you want to get categories name. See this mongoose documentation link on populate