使用mongoose填充不会返回有针对性的ref collection

时间:2018-04-27 02:23:09

标签: javascript node.js mongodb mongoose

我有2个集合,一个是Credit,另一个是User

信用

enter image description here

用户 enter image description here

正如您所见,信用卡的userId与用户的_id相同。检索该用户时如何检索信用文档?我已尝试过模式参考,但我没有获得信用数据,如此

exports.getUser = async function(req, res) {

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

  res.json(user)
}

CreditSchema

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

UserSchema

const UserSchema = new Schema({
  fullName: {
    type: String
  },
  // etc.....
  credit: {
    type: Schema.Types.ObjectId, 
    ref: 'Credit'
  }
})

0 个答案:

没有答案