如何使用猫鼬从Mongo中的多个集合中获取数据

时间:2019-05-14 10:02:24

标签: node.js mongodb mongoose mongoose-populate

当个人资料中的数据存储在多个集合中时,如何显示这些资料

尝试了此link

 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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

尝试这样填充:

.populate([
    {path:'category',model:'categoryMasterCsv'},
    {path:'subscriptionPlan',model:'planMasterCsv'},
    {path:'medicine',model:'kushalaUser'}])

这是我每天使用的方法。