如何根据猫鼬聚合中的条件显示字段值?

时间:2021-01-07 09:36:27

标签: node.js mongodb mongoose aggregate pipeline

我有一个架构 Schema A,其中的字段为:

const SchemaA = new Schema(
  {
    name: { type: String, required: true },
    id: { type: String, required: true },
    date: { type: Date, required: true },
    docA: {
      location: { type: String },
      key: { type: String, required: true }
    },
    team: [
      {
        docB: {
          location: { type: String },
          key: { type: String }
        },
        new: { type: Boolean, default: false },
        person: [
          {
            id: { type: Schema.Types.ObjectId, ref: 'Person' },
            isAccepted: { type: Boolean, default: false },
          }
        ]
      }
    ]
  },
  {
    timestamps: true
  }
);

然后我有一个聚合查询来获取数据。

      .lookup({
        localField: 'id',
        from: 'schemaas',
        foreignField: '_id',
        as: 'schemaa'
      })

所以在获取数据时我想检查:

If the schema has a team --> get the new team(There will be only 1 new team) --> 
if the new team has persons --> if isAccepted is false then show **docB**. 
Only if the condition matches show **docB** else every time show **docA** 

我尝试在使用匹配、过滤器的查找中使用管道,但似乎不是一个很好的方法。

对解决问题的任何帮助将不胜感激。谢谢

0 个答案:

没有答案