两个ObjectId之间的猫鼬虚拟引用

时间:2020-08-08 00:47:30

标签: javascript node.js mongodb mongoose

我知道可以使用对外部ObjectId的本地_id创建虚拟引用,但是可以对外部ObjectId使用本地ObjectId吗?

我正在尝试确定我的某个地方是否有错误,或者由于无法正常工作而无法实现。

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

const ProfileSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user',
  },
  bio: {
    type: String,
    max: 500,
  }
});

ProfileSchema.virtual('posts', {
  ref: 'Post',
  localField: 'user',
  foreignField: 'user',
});

// query
const profile = await Profile.findOne({
  user: req.user.id,
}).populate('posts')

1 个答案:

答案 0 :(得分:0)

是可以的,但是您需要向架构中添加{ toJSON: { virtuals: true } }

const ProfileSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
    },
    bio: {
      type: String,
      max: 500,
    },
  },
  {
    toJSON: { virtuals: true },
  }
);

来自文档:

请记住,默认情况下,toJSON()输出中不包含虚拟函数。如果要在使用依赖于JSON.stringify()的函数(例如Express的res.json()函数)时显示填充的虚拟对象,请在架构的toJSON选项上设置virtuals:true选项。

https://mongoosejs.com/docs/populate.html#populate-virtuals