1

I have a question ... I have a schema like this :

const chatSchema = new Schema({
[...]
  title: {
        type: String,
        required: true
    },
   message: [
    {
      content: {
        type: String,
        required: true
      },
      creator: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'User'
      }
    }
  ],
[...]
});

in my Node backend, how can I have access to my creators instances inside my message array ? I don’t know how to write the query with populate ...

Thank you all ! :-)

Simon Busch
  • 21
  • 1
  • 4
  • 1
    Does this answer your question? [Populate nested array in mongoose](https://stackoverflow.com/questions/19222520/populate-nested-array-in-mongoose) – eol Feb 20 '21 at 08:40

3 Answers3

0

use the following command:

...after importing chatSchema as maybe chats

module.exports.populateCreator = (req, res) => {
  chats.findOne({chatID})
    .populate({
      path: 'message',
      populate: {
        path: "creator"
      }
    })
    .then(chats => res.json(chats))
}
0

You can use like this

Chats.find(query)
  .populate({ 
     path: 'message',
     populate: {
       path: 'creator'
     } 
  })
  .exec(function(err, docs) {});
Ankita Kuchhadiya
  • 1,255
  • 6
  • 16
0

the query you are looking for is:

https://mongoplayground.net/p/2dpeZWsXR-V

db.booking.aggregate([
  {
    "$match": {
      id: "61fdfeef678791001880da25"
    }
  },
  {
    $unwind: "$cart"
  },
  {
    "$lookup": {
      "from": "products",
      "localField": "cart.product",
      "foreignField": "id",
      "as": "prod"
    }
  },
  {
    "$unwind": "$prod"
  },
  {
    "$project": {
      id: 1,
      status: 1,
      cart: [
        {
          id: "$cart.id",
          date: "$cart.date",
          timeSlots: "$cart.timeSlots",
          product: {
            id: "$prod.id",
            name: "$prod.name",
            
          }
        }
      ],
      
    }
  }
])
Rafiq
  • 8,987
  • 4
  • 35
  • 35