【问题标题】:Update nested array of Objects in Mongoose更新 Mongoose 中的嵌套对象数组
【发布时间】:2020-12-14 15:41:30
【问题描述】:

我需要更新位于“菜单”(模型)架构中的“类别”数组。 我想更改特定类别的名称。

“类别”架构只是一个架构 - 不是模型... 这段代码在一个nosejs服务器中

这是我的架构:

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

“类别”架构:

  const categorySchema = new mongoose.Schema(
  {

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

  {
    timestamps: true,
  }
)

我尝试这样做:

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

只是在猫鼬中无法理解

请帮忙

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    在你的 menuSchema “categories”中应该是一个 objectId 数组,引用其他模式,如

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

    然后填充您想要获取类别名称的类别。看到这个mongoose documentation link on populate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多