mongodb Mongoose的问题:populate不是函数

njthzxwz  于 2023-04-05  发布在  Go
关注(0)|答案(2)|浏览(201)

我有这段代码来创建一个新的注册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);

当我发送一个post请求到insomnia时,显示这个错误:有人能帮帮忙吗

col17t5w

col17t5w1#

您需要.find.findOne,它将从DB中检索并填充刚刚创建的文档:

await Registration
      .findOne({user: user_id})
      .populate('event')
      .populate('user', '-password')
      .lean() // faster, returns simple JSON
      .exec(); // returns a true Promise
4jb9z9bj

4jb9z9bj2#

我也有同样的问题

const Registration = require("../models/registration");

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

    console.log(user_id, eventId, date);

    const registration = await Registration.create({
      user: user_id,
      event: eventId,
      date
    });
  
    // NOT WORKING - event and user not populating
    // await registration
    //   .populate('event')
    //   .populate('user',"-password")
    //   .execPopulate();

    await registration
      .findOne({user: user_id})
      .populate('event')
      .populate('user', '-password')
      .lean() // faster, returns simple JSON
      .exec(); // returns a true Promise

    return res.json(registration)
  }
};

相关问题