0

I have this code to create a new registration on RegistrationController, and the Registration Model

const Registration = require('../models/Registration');

module.exports = {
  async create(request, response) {
    const { user_id } = request.headers;
    const { eventId } = request.params;
    const { date } = request.body;

    const registration = await Registration.create({
      user: user_id,
      event: eventId,
      date
    });

    await registration
      .populate('event')
      .populate('user', '-password')
      .execPopulate(); //PROBLEM HERE

    return response.json(registration);
  },
const mongoose = require('mongoose');

const RegistrationSchema = new mongoose.Schema({
  date: String,
  approved: Boolean,
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  event: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Event"
  }
});

module.exports = mongoose.model('Registration', RegistrationSchema);

When i send a post request to insomnia, this error is shown: (node:6260) UnhandledPromiseRejectionWarning: TypeError: registration.populate(...).populate is not a function. Can somebody help?

  • I don't think you can populate after create/fetch. Can you try and create it, save it, then use `await Registration.find({ ... }).populate(....)`? – Ollie Dec 03 '21 at 14:12

1 Answers1

0

You need .find or .findOne, it will retrieve and populate from the DB the document that was just created :

await Registration
      .findOne({user: user_id})
      .populate('event')
      .populate('user', '-password')
      .lean() // faster, returns simple JSON
      .exec(); // returns a true Promise
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63