从Mongoose find()查询返回的文档数组中查找不同的值



目标是从Mongoose find((查询检索的文档数组中查找Model字段的不同值。

为什么我觉得与众不同:在UI上将这些值用作过滤器(选择选项(。

IMP需要注意:该查询可以返回大约10000多个文档。因此,性能也是选择方法的一个标准。

这是带有字段的模型,要为其找到不同的值

const serviceLogSchema = mongoose.Schema({
....
calYear: { type: Number, required: true },
calMonth: { type: Number, required: true },
FY: { type: String, required: true },
servStatus: { type: String, required: true },
servCat: { type: String, required: true },
dueMonth: {type: String, required: true},
rm: { type: String },
compCat: { type: String },
compGroup: { type: String },
execName: { type: String },
approver: { type: String },
paytStatus: { type: String },
...
});

以下是用于每个字段的当前工作方法。但这会对数据库进行多次调用,因此会减慢进程。

// this code is repeated for each of the field
arrCompCat = await ServiceLog.distinct('compCat');
if(!arrCompCat) {
arrCompCat = [];
} else {
if(arrCompCat.length = 1 && arrCompCat[0] === '') {
arrCompCat = [];
} else {
arrCompCat.sort();
}
}

在其他几个线程中,我看到了以下从数组中获取不同值的方法。

let arrCompCat = [ ...new Set(fetchedDocs.map(e => e.compCat)) ]

但我得到了以下错误。

object is not iterable (cannot read property Symbol(Symbol.iterator))

fetchedDocs是find查询的结果。如果能做到这一点,那将是一个很好的选择,因为我只会从数据库中检索一次文档,然后对该文档数组进行操作,而不是单独调用数据库。

我会使用映射或过滤方法,但这也可能是性能密集型的。对于这种情况,有什么有效的方法吗?

如果您担心性能,可以使用.distinct('compCat').lean().exec();开始改进。lean返回简单的JSON,而不是Mongoose对象,因此它更轻、更快。而exec返回的是一个真正的Promise,而不是像这样一个无用的Promise。

最新更新