motchezz
motchezz

Reputation: 153

node js, mongodb populate the populated

I've hit a wall in my server when I needed to get data from my server. The following represents my schemas:

Schema one:{
name: String
}
Schema two:{
code:String,
name_id: refid: schema One
}
Schema three:{
phone:number
code:[refid: Schema two]
}

If I needed data from schema three, and the objects from object ids that are saved in the code array I would use populate and I would get the object referenced by object id. Question is is it possible to populate the populated data? If populate schema three I would get objects such as:

{phone : 000911,
code: :{code:String,
name_id: refid: schema One}

in the previous example I want to populate the name id, is that possible?

Upvotes: 0

Views: 77

Answers (1)

TGrif
TGrif

Reputation: 5931

With Mongoose, you can populate your schema with dot notation like this:

const One = new Schema({
  name: String
})

const Two = new Schema({
  code: String,
  name: {
    type: Schema.ObjectId,
    ref: 'One'
  }
})

const Three = new Schema({
  phone: number
  code: [{
    type: Schema.ObjectId,
    ref: 'Two'
  }]
})


Three.find((err, three) => {
  if (err) console.log(err)
  console.log(three)  
  // => {
  //      phone : "the phone number from schema Three",
  //      code: {
  //        code: "the code from schema Two",
  //        name: "the name from schema One"
  //      }
  //    }
})
.populate('code.name')

Upvotes: 1

Related Questions