0

I have the following Mongoose schema:

const tripSchema = new Schema({
    events: [{
        eventId: {
            type: Schema.Types.ObjectId,
            ref: 'Event',
            required: true
        },
        quantity: {
            type: Number,
            required: true
        }
    }],
    user: {
        email: {
            type: String,
            required: true
        },
        userId: {
            type: Schema.Types.ObjectId,
            required: true,
            ref: 'User'
        }
    }
})

and basically I'd like to get the events and populate then pass along the results. I get the results but after I map the asynchronicity is messing me up.

  Trip.find({
      'user.userId': mongoose.Types.ObjectId(req.user._id)
    })
    .then(trips => {
     // A. I get trips here
      return trips.forEach(
        trip => {
          trip.populate('events.eventId')
            .execPopulate()
        }
      )
    }).then(trips => {
      //B. trips is undefined
      res.render('standard/trips', {
        path: '/trips',
        pageTitle: 'Your Trips',
        trips
      })
    })
    .catch(err => console.log(err))

So at point A. trips is what it's supposed to be I believe, but at point B it is undefined. I get that this is an async issue, just not sure how to resolve this. Please help. Thanks.

Rik

Rik
  • 1,870
  • 3
  • 22
  • 35
  • `Array.prototype.forEach` is for side effects (doesn't return a value) - try replacing with `Array.prototype.map` – ic3b3rg Jan 05 '19 at 01:52
  • I'm wondering now if there is a way to populate the whole array in one populate call from the database instead of making so many populate calls – Rik Jan 05 '19 at 01:56
  • 1
    I'm not familiar with mongoose, but I took a quick look at the docs - it looks like you should be able to [populate across multiple levels](https://mongoosejs.com/docs/populate.html#deep-populate) – ic3b3rg Jan 05 '19 at 02:03
  • 1
    omg you're right, I don't even need to do the map, mongoose will do it for me. Trip.find({ 'user.userId': mongoose.Types.ObjectId(req.user._id) }) .populate('events.eventId').then() does the trick – Rik Jan 05 '19 at 02:23

0 Answers0