簡體   English   中英

如何逐一填充 mongoose 架構

[英]how to populate a mongoose schema on one by one

我嘗試填充 mongoose 架構。 我有 3 個模式,分別命名為 ClothBrandSchema、clothSchema、userSchema。

布料品牌架構:

 name: {
    type: String,
    required: true,
  },
  Origin: String,
 }
const ClothBrand = new mongoose.model("ClothBrand", ClothBrandSchema);

第二個是:clothSchema:

{
  category: {
    type: String,
    enum: ["Ladies", "Mens","Kids","Boys","Girls"],
  },
  name: String,
  brand:[{
    type:mongoose.Schema.Types.ObjectId,
    ref:"ClothBrand"
  }]  //many brands have same type of cloth so define array of brands name
}
const Cloth = new mongoose.model("Cloth", clothSchema);

第三個是:userSchema:

{
  name: {
    type: String,
    required: true
  },
    cloth: {
      type:mongoose.Schema.Types.ObjectId,
      ref:"Cloth"
    }
}],
}
const User = new mongoose.model("User", userSchema);

所以我想當我得到用戶的數據然后我得到這樣的:用戶:

{
    "_id": "62df18bdb19a5a056a18c0c9",
     "name": "ABC",
     "cloth": {
          "_id": "62df12525e2c53efd6afe2c5",
           "category": "Boys",
           "name": "Jeans",
           "brand":[  
               {
                "name": "xyz"
                "Origin": "xyz"
               },
               {
                "name": "xyz"
                "Origin": "xyz"
               }
               ...
             ] // somewhere not written an object id so ignore it
         },

那么有沒有可能,那么解決方案是什么。 我如何在我的節點 js 代碼庫中編寫查詢。

我在幾個小時內從 mongoose 官方文檔mongoose docs on populate得到了答案

所以代碼是這樣的:

            user.findOne({ name: 'ABC' }).
            populate({
                path: 'Cloth',
                populate: { path: 'brand' }
              })
                .then(result => {                  
                   res.json(result)
                })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM