首页 > 解决方案 > 猫鼬不居住

问题描述

我正在尝试填充我的一个模型,但它不起作用。这是我的卡片架构:

const CardSchema = new mongoose.Schema({
  text: {
    type: String,
  },
  wrap: {
    type: String,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  }
});

module.exports = mongoose.model('Card', CardSchema);

这是我的控制器:

exports.getCards = asyncHandler(async (req, res, next) => {
  const cards = await Card.find({}).populate('user').exec();
  
  res.status(200).json({
    success: true,
    count: cards.length,
    data: cards,
  });
});

它确实返回卡片,但没有任何用户字段。用户架构导出为“用户”

标签: javascriptmongodbexpressmongoose

解决方案


您在引用用户集合时定义模型时犯了一个小错误,请删除单引号

模型定义应如下

const CardSchema = new mongoose.Schema({
  text: {
    type: String,
  },
  wrap: {
    type: String,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: User, // Replace 'User' with User
  }
});

module.exports = mongoose.model('Card', CardSchema);

推荐阅读