首页 > 解决方案 > 两个 ObjectId 之间的 Mongoose 虚拟引用

问题描述

我知道可以使用本地 _id 创建对外部 ObjectId 的虚拟引用,但是是否可以使用本地 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')

标签: javascriptnode.jsmongodbmongoose

解决方案


是的,这是可能的,但您需要添加{ 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


推荐阅读