首页 > 解决方案 > 猫鼬根据条件填充

问题描述

我的服务使用 MongoDB 和 Mongoose。我有两个数据库:用户和帖子。在 Posts 架构中,我有参数:

我无法解决问题:当我从 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();
});

标签: mongodbmongoosemongoose-schemamongoose-populate

解决方案


推荐阅读