【问题标题】:Check against multiple fields when using Mongoose Virtual schema?使用 Mongoose 虚拟模式时检查多个字段?
【发布时间】:2019-01-25 16:37:49
【问题描述】:

我有点坚持试图找出在我的数据库中填充虚拟模式的最佳方法。在这种情况下,我想检查多个字段,但我不知道任何方法或替代方法。

我曾希望我可以在虚拟模式的“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',
        }]
      });

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 2018-08-31
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2020-05-16
      • 2016-03-24
      相关资源
      最近更新 更多