mongodb - 猫鼬根据条件填充
问题描述
我的服务使用 MongoDB 和 Mongoose。我有两个数据库:用户和帖子。在 Posts 架构中,我有参数:
- "author",包含来自用户数据库的 userId
- "anonymous",一个布尔参数,显示帖子是否是匿名的。
我无法解决问题:当我从 Posts DB 请求数据时,我只想在“作者”参数中填充非匿名帖子的作者,对于匿名帖子,我想返回null或不返回此参数全部。
我尝试使用“匹配”,但它不起作用。
我怎么解决这个问题?
谢谢你。
代码示例:
const postSchema = mongoose.Schema(
{
author: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
anonymous: {
type: Boolean,
required: true,
default: false,
},
content: {
type: String,
required: true,
},
date: {
type: Date,
required: true,
default: Date.now,
},
},
{
timestamps: true,
}
);
对于我使用 pre 的人群:
postSchema.pre(/^find/, function (next) {
this.populate({
path: 'author',
select: '_id login',
});
next();
});
解决方案
推荐阅读
- r - 在 R 中查找概率
- android - 如何在 Flutter 中创建 HTTP 服务器应用程序?
- vue.js - Quasar q-icon 在资产文件夹中使用图标
- react-native - react-native 没有 expo 或在 expo 中使用库
- html - 如何在文本元素之间添加水平线
- pyspark - 将 Pyspark 数据框保存到没有标题的 csv 中
- go - 复数的离散积分会产生错误的结果
- python - 如何比较特定列中两行的值?
- javascript - TypeError:无法读取未定义的属性“contentWindow”
- flutter - 如何使用内置值创建嵌套对象