我有两个模型,称为会话和未读计数。我需要从另一个表获取特定的会话计数。下面是我的两个 Mongodb 模型。
var UnreadCountSchema = new mongoose.Schema({
userId: { type: String, required: true },
sessionId: { type: String, required: true},
unreadCount: { type: Number, required: true, default: 0 },
isDeleted: { type: Boolean, required: true, default: 0 },
}, { timestamps: true });
module.exports = mongoose.model("UnreadCount", UnreadCountSchema);
var SessionSchema = new mongoose.Schema({
name: { type: String, required: false },
subject: { type: String, required: false },
sessionCode: { type: String, required: false },
}, { timestamps: true });
module.exports = mongoose.model("Session", SessionSchema);
我没有使用引用和关系。当我获取会话时,我需要进行计数。我尝试过查找它不起作用。建议我一种方法来做到这一点
以下是我执行的代码。计数在那里,但我没有得到结果。
const response = await SessionModel.aggregate([
{
$match: query,
},
{
$lookup: {
from: "UnreadCount",
localField: "_id",
foreignField: "sessionId",
as: "unreadCounts",
},
},
{
$addFields: {
unreadCount: {
$cond: {
if: { $gt: [{ $size: "$unreadCounts" }, 0] },
then: { $arrayElemAt: ["$unreadCounts.unreadCount", 0] },
else: 0,
},
},
},
},
// Optionally sort the sessions by lastMessage createdAt
// { $sort: { "lastMessage.createdAt": -1 } },
])
我们必须使用在 Mongodb 数据库中创建的模型名称,并将对象 id 转换为字符串。根据我们要比较的数据类型。
代码中提到的模型名称在数据库中是unreadCount,就像unreadcounts。
{
$lookup: {
from: "unreadcounts",
let: { id: { $toString: "$_id" } },
pipeline: [
{
$match: {
$expr: {
$eq: ["$sessionId", "$$id"]
}
}
}
],
as: "unreadcounts"
}
}
将评论中的答案写为答案帖。
确保两个字段必须具有相同的类型才能进行相等匹配。在这种情况下,您可以使用
$lookup
和 pipeline 将 UnreadCount 集合中的 sessionId
转换为 ObjectId
。
{
$lookup: {
from: "UnreadCount",
let: {
sessionId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$sessionId",
{
$toObjectId: "$sessionId"
}
]
}
}
}
],
as: "unreadCounts"
}
}
或者您可以将 Session 集合中的
_id
转换为 string
类型。
{
$lookup: {
from: "UnreadCount",
let: {
sessionId: { $toString: "$_id" }
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$sessionId",
"$sessionId"
]
}
}
}
],
as: "unreadCounts"
}
}