I have two models called session and unreadcount. I need to get that particular session count from another table. below are my two Mongodb models.
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);
I have not used referencing and relation. I need to get a count when I fetch the session. I have tried lookup it doesn’t work. suggest me a way to do this
The following is my code that i executed. count is there but iam not getting the result.
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 } },
])
2
Answers
we have to use the model name that was created in Mongodb database and also convert the object id to a string. according to the type of data we are going to compare.
The model name mentioned in code was unreadCount in database it was like unreadcounts.
Wrote the answer from the comment as the answer post.
Ensure that both fields must have the same type for the equality match. In this case, you can use the
$lookup
with pipeline to convert thesessionId
from the UnreadCount collection toObjectId
.Or you can convert the
_id
from the Session collection asstring
type.