我的应用中有以下代码:
const response = {
created: await eventModel.count({ author: uid }).exec(),
participated: await eventModel.count({ participants: uid }).exec(),
interested: await eventModel.count({ interested: uid }).exec()
};
我想知道如何只使用一个请求获得相同的输出。
以下是模型:
const eventModel = mongoose.model("Event", new mongoose.Schema({
author: mongoose.Schema.Types.ObjectId,
interested: [mongoose.Schema.Types.ObjectId],
participants: [mongoose.Schema.Types.ObjectId],
title: String
}));
有没有办法正确地做到这一点?
答案 0 :(得分:1)
如果您的问题是how do I get data from mongo and only make 1 query for a given criteria?
,那么如果没有更明确的解释,那么就是这样。
const eventModelCounts = eventModel.aggregate(
[
{ $group : { _id : { author: uid, participants: uid, interested: uid }, uid: { $sum: 1 } }}
]
).exec(function(err,data){
count = data;
console.log("this is data aggregate:",data);
callback();
});
基本上你在感兴趣的字段上应用聚合。