首页 > 解决方案 > 如何使用 mongoose 从 Mongo 中的多个集合中获取数据

问题描述

当这些数据存储在多个集合中时,我如何显示配置文件的详细信息数据

试过这个链接

 const profile = await userKushala
      .find({_id: '5cd407c741f9e7373f10362c'})
      .populate({
        path: 'settingId',
        populate : {
            path : 'specialty',
          populate : {
            path: 'hospital_attached'
          }
        }
      })

// 第一个集合(基本信息)

const userRegisterSchema = new Schema({
userType: {
    type: String,
    required: true
},
mobile: {
    type: Number,
    required: true,
    unique: true
},
userId: {
    type: String,
    required: true
},
name: {
    type: String,
    required: true
},
email: {
    type: String,
    required: true
},
age: {
    type: Number,
    required: true
},
gender: {
    type: String,
    required: true
},
settingId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'providerSetting'
}
})

// 第二个集合(详细信息。)

const serviceProfileUpdate = new Schema({
   specialty :[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'specialtyMasterCsv'
}],
category: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'categoryMasterCsv'
}],
subscriptionPlan: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'planMasterCsv'
},
medicine: {
    type : mongoose.Schema.Types.ObjectId,
    ref: 'kushalaUser' 
}
})

//Mongo中的数据

{  
   "_id":{  
      "$oid":"5cd93ea6bd96e43664f49bf3"
   },
   "specialty":[  
      {  
         "$oid":"5cda85f26ffe60259a75ba17"
      },
      {  
         "$oid":"5cda85f26ffe60259a75ba18"
      }
   ],
   "category":[  
      {  
         "$oid":"5cda85f26ffe60259a75ba17"
      },
      {  
         "$oid":"5cda85f26ffe60259a75ba18"
      }
   ],
   "subscriptionPlan":{  
      "$oid":"5cda85f26ffe60259a75ba17"
   },
   "medicine":{  
      "$oid":"5cd407c741f9e7373f10362c"
   },
   "__v":{  
      "$numberInt":"0"
   }
}

预期结果将来自所有应获取的集合数据,但使用我的代码,它会给出结果直到专业,但之后它只打印 ObjectID

标签: node.jsmongodbmongoosemongoose-populate

解决方案


这就是我所做的,如果有人有更好的解决方案,它仍然可以工作,非常受欢迎。希望它可以帮助某人。

const profile = await userKushala
      .find({_id: '5cd407c741f9e7373f10362c'})
      .populate({
        path: 'settingId',
        populate : {
            path : 'specialty category subscriptionPlan medicine'
            }
      }) 

推荐阅读