当foreignField是一个数组时,猫鼬虚拟返回null

我有两种模式,一种用于记录,一种用于用户。 Users模式具有一个称为“ records”的数组,该数组引用Records模式。我想在Record模式中使用一个虚拟的“所有者”,它显示所有在“ records”数组中列出了Record的用户。

我尝试将“记录”放入“ {owns”虚拟”的foreignField中,但是当查询记录时,“所有者”只是显示为null

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String,required: true },records: [{ type: mongoose.Schema.Types.ObjectId,ref: 'Record' }]
});

const recordSchema = new mongoose.Schema({
  title: { type: String,required: true }
});
recordSchema.virtual('owners',{
  ref: 'User',localField: '_id',foreignField: 'records'
})
recordSchema.set('toObject',{ virtuals: true })

const User = mongoose.model('User',userSchema);
const Record = mongoose.model('Record',recordSchema);

mongoose.connect('mongodb://localhost/test')
  .then(() => Record.create({ title: 'Test Record' }))
  .then(record => User.create({
    records: [record.id],name: 'Test User',}))
  .then(user => {
    console.log(user);
    return Record.find();
  })
  .then(records => {
    console.log(records);
    return mongoose.disconnect();
  })
  .catch(err => {
    console.error(err);
    return mongoose.disconnect();
  });
hzh600606 回答:当foreignField是一个数组时,猫鼬虚拟返回null

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3130853.html

大家都在问