我的mongoDB数据库中有两个集合-
users
和
connections
.
每个
connection
有字段
user
其中包含
_id
一个
用户
储存在
用户
收藏。
我需要找到每个用户的连接总数,如果用户没有连接,它应该显示0作为他的总数。
还要查找连接数
date
字段不相等
''
每个用户。
我写了这段代码,它会重新显示每个用户的连接总数,但只对至少有一个连接的用户,没有连接的用户根本不会出现。。。
Connection.aggregate(
[
{
$group: {
_id: "$user",
total: { $sum: 1 },
withDate: { $sum: { $cond: { if: { $ne: ["$date", ""] }, then: 1, else: 0 } } }
}
},
{
$lookup: {
from: "users",
localField: "_id",
foreignField: "_id",
as: "users"
}
},
{
$unwind: "$users"
},
{
$project: {
Email: "$users.local.email",
"Last Edit": { $dateToString: { format: "%Y-%m-%d", date: "$users.local.lastConnectionEdit" } },
"Total Connections": "$total",
"Connections With Date": "$withDate"
}
}
],
function(err, dashboardData) {
if (err) {
console.log(err);
res.status(500).end({ error: "Error fetching stats from database" });
} else {
let csv = json2csv(dashboardData);
res.attachment("stats.csv");
res.status(200).send(csv);
}
}
);
连接架构:
active:Boolean,
info: {
name: String,
profileImg: String,
bio: String
},
connURL:String,
handle:String,
notes: String,
date: String,
value: {
type: Number,
min: 0,
max: 5
},
tags: [String],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
用户架构:
local: {
email: String,
password: String,
admin: Boolean,
snoozeAmount: Number,
snoozeInterval: String,
emailIntervalWeeks: Number,
emailIntervalDay: Number,
isVerified: { type: Boolean, default: false },
verifyToken: String,
passwordResetToken: String,
lastConnectionEdit: Date
}