首页 > 解决方案 > 在猫鼬模式中使用 ref 填充集合失败

问题描述

我想将信用收集填充到用户收集中,这是我的信用模式

const CreditSchema = new Schema({
  userId: Schema.Types.ObjectId,
  credit: {
    type: Number,
    default: 0
  },
  log: [String]
})

我的用户模式是这样的

const UserSchema = new Schema({
  fullName: {
    type: String,
    trim: true,
    required: true
  },
  email: {
    type: String,
    unique: true,
    lowercase: true,
    trim: true,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  credit: {type: Schema.Types.ObjectId, ref: 'Credit' } //I suspect something is not right here
})

为什么我在下面的用户对象中看不到信用?

const user = await User.findOne({_id: req.query.id})
.populate('credit')
.exec()

console.log(user) // credit field is not present?

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


推荐阅读