【问题标题】:how to populate nested array using mongoose如何使用猫鼬填充嵌套数组
【发布时间】:2021-10-15 22:33:20
【问题描述】:

假设我有这 2 个模式 具有一系列类别的公司架构

//category
export const CategorySchema = new mongoose.Schema({

    name: { type: String },
}, { timestamps: true });
//company
export const CompanySchema = new mongoose.Schema({
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    name:String,
    email:String,
    categories:{type: [CategorySchema], default: [] },
}, { timestamps: true });

将类别作为公司类别参考的产品架构

export const ProductSchema =new mongoose.Schema({
    name:String,
    category:{ type: Schema.Types.ObjectId, ref: 'Category' },
}, { timestamps: true })

是否可以从产品中填充类别? 我试过这段代码,但它不工作

const products=await this.productModel.find({}).populate({'path':"category","model":"Category"}) ``

【问题讨论】:

    标签: node.js mongodb mongoose nestjs mongoose-populate


    【解决方案1】:

    试试这个代码populate

    const products=await this.productModel.find({}).populate({'path':"category","model":"company.categories"}) 
    

    【讨论】:

      【解决方案2】:

      你需要的只是

      productModel.find({}).populate("category")
      

      【讨论】:

      • 这在类别中返回 null,因为它是一个嵌套文档
      • 不试试能不能输入首字母大写
      猜你喜欢
      • 2019-02-24
      • 2015-11-24
      • 2015-02-09
      • 1970-01-01
      • 2016-11-14
      • 2014-07-28
      • 2021-11-07
      • 2019-01-16
      相关资源
      最近更新 更多