【问题标题】:Problem from mongoose: populate is not a function来自猫鼬的问题:填充不是函数
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2015-07-13
    • 2016-10-10
    • 2020-01-17
    • 2014-04-19
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多