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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.