首页 文章

使用Mongoose Virtual架构时,请检查多个字段?

提问于
浏览
0

我试图找出在我的数据库中填充虚拟架构的最佳方法,我有点困惑 . 在这种情况下,我想检查多个字段,但我不知道有任何方法可以做到这一点或替代方法 .

我曾希望我可以在虚拟架构的'localField'和'foreignField'键中使用一些字符串数组,但事实并非如此 .

用户已保存“系列”_id,并且虚拟架构“联盟”获得用户进入的所有联赛,该联赛属于不同系列的联赛 . 我想只检索用户输入的联赛并且与用户的系列_id匹配...

正如您所看到的,此虚拟架构只返回用户输入的所有联赛,无论系列如何 . :(

有任何想法吗?我一直很困惑如何实现这一目标 .

const schema: mongoose.Schema = new mongoose.Schema({
        _id: {
          type: mongoose.Schema.Types.ObjectId,
          auto: true
        },
        username: {
          type: String,
          unique: true,
        },
        series: {
          ref: 'Serie',
          type: mongoose.Schema.Types.ObjectId,
          autopopulate: {
            maxDepth: 1,
            select: ['title']
          }
        }
      });

      schema.virtual('leagues', {
        ref: 'League',
        localField: '_id',
        foreignField: 'users',
        autopopulate: {
          maxDepth: 1,
          select: ['title', 'engineSize', 'host', 'series']
        }
      });

联盟架构看起来像这样

const schema: mongoose.Schema = new mongoose.Schema({
        _id: {
          type: mongoose.Schema.Types.ObjectId,
          auto: true
        },
        title: String,
        series: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Serie',
        },
        users: [{
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        }]
      });

1 回答

  • 0

    这是我使用getter检查mongoose中的多个字段的解决方案 .

    schema.virtual('motoduel').get(function () {
       return motoduelModel.findOne({
         event: this.series.upcomingEvent._id,
         riderGroup: this.riderGroup._id
       });
     });
    

相关问题