javascript - 两个 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')
解决方案
是的,这是可能的,但您需要添加{ 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 选项。
推荐阅读
- android - 获取目录甚至从图库中删除
- javascript - 如何在下一个 .then() 中访问日期 - 获取 api
- windows - Windows 10 上的 Symfony 5 安装一直运行旧版本
- c# - 从数组字符串中删除多余的字符串
- sql - 在 shell 脚本中读取所有出现的 mm/dd/yyyy 并将其转换为 dd-MON-yyyy
- time - 我正在为天气应用程序使用 Dark Sky API,这次是什么意思?
- c++ - 前向迭代器上的 stable_partition
- python - “表 x:Yz:用户 123@developer.gserviceaccount.com 没有表 project_x:yz 的 bigquery.tables.get 权限”
- wpf - Visual Studio 2019 的 Visio 绘图控件
- deb - 在 Debian 安装上安装 systemd 服务