node.jsmongodbmongoose

mongo db from on model to another model


I'm using Mongo DB for my database and I'm using mongoose for managing it in my backend code.

I have 3 models in this details.

  1. the first model is Media for getting files form users.
  2. the second is folder. this item has many items. one of this items is medias. in other words user should make a folder and in the folder, enter 3 files.
 medias: {
      type: [Schema.Types.ObjectId],
      ref: "Media",
   },
  1. the third model is order. the user when added at least one folder, he can submit an order. order has many items. one of them is folders.
  folders: {
      type: [Schema.Types.ObjectId],
      ref: 'Folder',
      required: true,
   },

so. we have medias in folder and we have folders in order.

the question is this. when I want to see an order details, I want to see my folders and it's medias.

I can use populate for accessing all folders of an order. but how can I access medias of any folder?

how can I make populate in populate?

const founded_item = await Order.findById(goal_id)
         .populate({ path: 'folders', model: Folder, })

Solution

  • To populate nested references like medias inside folders when querying an Order, you need to use populate within populate in Mongoose.

    const founded_item = await Order.findById(goal_id)
      .populate({
        path: 'folders',
        model: 'Folder',
        populate: {
          path: 'medias',
          model: 'Media'
        }
      });