将嵌套文档的子集添加为猫鼬查询中的新字段

时间:2019-05-02 08:48:56

标签: node.js mongodb mongoose

这是我的模型架构

const autopopulate = require('mongoose-autopopulate')

const A = new mongoose.Schema({
    someId: String,
    bs: [{ type: mongoose.Schema.Types.ObjectId, ref: 'B', autopopulate: true }]
}, { timestamps: true })

const B = new mongoose.Schema({
    someData: String,
    cs: [{ type: mongoose.Schema.Types.ObjectId, ref: 'C', autopopulate: true }]
}, { timestamps: true })

const C = new mongoose.Schema({
    name: String
}, { timestamps: true })

A.plugin(autopopulate)
B.plugin(autopopulate)
C.plugin(autopopulate)

我有一个A,包含一个B的数组,每个B包含一个Cs的数组。

我查询A以获得其Bs:

res.json( (await A.findOne({somecondition})).bs )

我得到这样的东西:

[{
  someDatas: "...",
  cs: [{name: "h"}, {name: "e"}, ....]
},
.....
]

我想在C中基于C在每个B中添加一个字段,如下所示:

[{
  someDatas: "...",
  cs: [{name: "h"}, {name: "2"}, ....], // keep all the cs
  csThatAreNumbers: [{name: "2"}, {name: "8"}] // add a field containing a part of cs based on a condition
},
.....
]

有没有一种方法可以直接从猫鼬查询中执行此操作,还是必须在查询后以编程方式处理数据?

0 个答案:

没有答案