gpt4 book ai didi

node.js - Mongoose:从 2 个集合获取数据

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:26 24 4
gpt4 key购买 nike

我有 2 个模型事件用户,我想获得参加每个事件的用户数量,例如。

//expected result
[
{
"users": 50,
"eventName": "Event one"
},
{
"users": 46,
"eventName": "Event two"
},
{
"users": 63,
"eventName": "Event three"
}
]

架构是

//events
const eventSchema = new Schema(
{
name: String,
location: String,
landmark: String,
dateTime: String,
status: {type:String, default: 1} //0-finished 1-live
}
);

//users
const userSchema = new Schema(
{
name: String,
image: String,
email: {type: String, lowercase: true},
password: String,
events: [{type: Schema.Types.ObjectId, ref: 'events'}] //containes ids of events attended
}
);

我如何使用 mongoose 或 mongoDB 进行查询,下面是我正在尝试的方法

usersPerEvent: async (req, res, next) => {

const events = await Event.find({});
const users = await User.find({}).count();

//expected result
res.status(200).json({
users: count,
eventName: eventName
});
},

期待急需的帮助

谢谢

最佳答案

您可以使用$lookup接下来是 $unwind & $group统计参加事件的用户数量。

类似于

User.aggregate([
{"$lookup":{
"from":"events", // name of the collection
"localField":"events",
"foreignField":"_id",
"as":"events"
}},
{"$unwind":"$events"},
{"$group":{
"_id":"$events.name",
"users":{"$sum":1}
}},
{"$project":{
"_id":0,
"eventName":"$_id",
"users":1
}}
]).exec(function() {...})

关于node.js - Mongoose:从 2 个集合获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com