0

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?

3
  • Try using $lookup stackoverflow.com/questions/9621928/… Commented Oct 17, 2017 at 8:38
  • Is Schema three code: refid: Schema One or Two ? Also are you using Mongoose ? Commented Oct 17, 2017 at 9:37
  • schema three code is referenced from schema two, yes am using mongoose Commented Oct 17, 2017 at 9:42

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

and if i needed a another population, let's say a zero schema, and i needed to populate from three to two to one zero
That will work with an array too. If you need to add a third level, simply add another dot property. See populate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.