【问题标题】:populate document field in getter在 getter 中填充文档字段
【发布时间】:2022-01-18 03:05:17
【问题描述】:

我正在尝试解决架构上有两个字段可能相互冲突的问题。因此,一个字段可能是有效的,但是一旦您考虑另一个字段,它就不再有效了。出于各种原因,将这两者结合起来是没有意义的。

因此,我们可以选择在客户端处理该比较,或者通过实施一些较低级别的东西来过滤掉无效文档。即

const schema = new Schema({
  isValid: Boolean,
  other: {
    isValid: Boolean
  }
})

如果一个文档是无效的,那么它应该被认为是未定义的

// assume these are the contents of the collection
const Raw = [
  {
     isValid: true,
     other: {
        isValid: true
     }
  },
  {
     isValid: false,
     other: {
        isValid: true
     }
  },
  {
     isValid: true,
     other: {
        isValid: false
     }
  },
]

const data = await schema.find({});

data.length === 1; // true
data[0] === Raw[0]; // true

也就是说,每当您请求一个将检查该文档是否有效的文档时,我都会尝试实现一个 getter。但是,在这种特殊情况下,other 是另一个集合的 id。所以为了确定它是否有效,我需要填充它。

最好的方法是什么?

【问题讨论】:

  • 以及是什么使其他引用的文档有效?您可以在聚合中使用 $lookup 并在该阶段之后触发 $match 来检查它
  • 主要是因为我想对任何类型的访问(包括聚合)都这样做

标签: mongoose schema getter populate


【解决方案1】:

我重建了问题,请确保将字段名称替换为您拥有的名称

这是聚合结果:只有一个两者都为真,因此剩下一个文档:

聚合代码如下所示:

db.collection.aggregate([
  {
    '$lookup': {
      'from': 'products', // The other collection
      'localField': 'otherId', // The matching field in this one
      'foreignField': '_id', // The matching field in products
      'as': 'otherId' // Overwrite otherId with the populated document
    }
  }, {
    '$match': { 
      'valid': 'true', // Match this fields value
      'otherId.valid': 'true' // Match the field from the other collection
    }
  }
])

还要注意,$lookup 总是返回一个数组,如果不需要,可以用 $unwind 链接它。

如果数据库非常大,您可以在前后进行匹配以防止不必要的查找:

[
  {
    '$match': {
      'valid': 'true'
    }
  }, {
    // ... lookup as above
  }, {
    '$match': {
      'otherId.valid': 'true'
    }
  }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2021-03-22
    • 2020-02-19
    • 2021-07-26
    • 2019-07-17
    相关资源
    最近更新 更多