'How can I populate within Populate in Mongoose?

I'm making a Food Ordering App where User can place an order and that order can be received on store's end.

I want that using just the ItemID from Order, I can get the whole ItemData(w/ corres.) ItemID

I've used MONGODB with various Schemas given below:

1.ITEMSCHEMA : to store a product

const itemSchema = new mongoose.Schema({
  name: {           // FoodItemName:ex-"Shahi Panner"
    type: String,
    required: true,
  },
  cuisine_category:{ // CusineType:ex-"Thai","Chinese"
    type: String,
  },
  item_type: {    // Item Category:ex-"VEG/NON-Veg"
    type: String,
    required: true,
    default: "Veg",
  },
  price: {        // ItemPrice:ex-"Rs10.00"
    type: Number,
    required: true,
  },
  description: {  // Description of FoodItem
    type: String,
  },
  store_id: {     // stores the corres.Store
    type: mongoose.Schema.Types.ObjectId,  
    required: true,
    ref: "storeModel",   //For joining with STOREmodel
  },
});

2.ORDERSCHEMA: Schema to be followed while ordering by USER

const orderSchema = new mongoose.Schema({
  item_id: {           //Here I'm storing the corresponding Item-Id which is ordered by User
    type: mongoose.Schema.Types.ObjectId,
    ref: "itemModel",
  },
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "userModel",
  },
  order_id: {
    type: mongoose.Schema.Types.ObjectId,
  },
  quantity: {
    type: Number,
    default: 1,
  },

});

On User Side:

    await req.user.populate({
      path: "myorders",
    });

In UserSchema

userSchema.virtual("myorders", {
  ref: "OrderModel",
  localField: "_id",
  foreignField: "user_id",
});

The above piece of code is just getting the orders(w/ ItemID)simply not the actual item names


What I want to do?

I want that when store/user fetches the orders(corresponding to them) it should display the actual item with all properties as followed in ItemSchema i.e. from using that ItemID present in Order I can get the corresponding items so that I can calculate price for the corresponding order.

I want to use the Populate Method in Mongoose to join the table and get result

Please do tell me what should I do? Any changes in DBSchema, any nested populate method ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source