【发布时间】:2021-12-03 14:10:12
【问题描述】:
我有这段代码可以在 RegistrationController 上创建一个新的注册,以及注册模型
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);
当我向 insomnia 发送 post 请求时,会显示此错误:
(node:6260) UnhandledPromiseRejectionWarning: TypeError: registration.populate(...).populate is not a function。有人可以帮忙吗?
【问题讨论】:
-
我认为您无法在创建/获取后进行填充。你可以尝试创建它,保存它,然后使用
await Registration.find({ ... }).populate(....)吗?
标签: javascript node.js mongodb mongoose insomnia