[英]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 “类别”架构只是一个架构 - 不是 model ......此代码位于nosejs服务器中
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只是在 mongoose 中无法理解这一点
Please help请帮忙
In your menuSchema "categories" shoud be an array of objectId refer to other schema like在你的 menuSchema “类别”应该是一个 objectId 数组,指的是其他模式,如
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
请参阅有关填充的此 mongoose 文档链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.