How to implement Mongoose Populate in my scenario?

67 views Asked by At

I am a relatively new to using the populate feature in Mongoose. I have the need to populate the "_id" field of my "Customer" model with the list of Orders made by this customer. Here are the Schemas.

Customer_Schema = {
 name : string,
 phone : string,
 email : string

Orders_Schema= {
 customerID : string,  // This is the object ID of the customer from the "Customer_Schema"
 phone : string,
 email : string

Now I would like to know how to setup the "refs" in the Schemas and how to execute the populate command. For my end result I would like to get the Customer with all the order data under their "customerID".

Thanks.

1

There are 1 answers

2
Nazrul Chowdhury On

You can set up a reference in the orderSchema that points to the "Customer" model.

// Customer Schema
const customerSchema = new mongoose.Schema({
  name: String,
  phone: String,
  email: String
})
// Order Schema
const orderSchema = new mongoose.Schema({
  customerID: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Customer' // Reference to the Customer model
  },
  phone: String,
  email: String
})
// Define the models. Export models if necessary...
const Customer = mongoose.model('Customer', customerSchema)
const Order = mongoose.model('Order', orderSchema)

Now you can use populate to get customer along with orders,

Customer.findOne({ /* your query criteria .... */ })
  .populate('customerID') // 'customerID' should match the field name in the orderSchema
  .exec((err, customerWithOrders) => {
    if (err) {
      console.error(err)
      return
    }

    console.log('Customer with orders:', customerWithOrders)
  })