skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    {
                $lookup: {
                    from: "unreadcounts",
                    let: { id: { $toString: "$_id" } },
                    pipeline: [
                        {
                            $match: {
                                $expr: {
                                    $eq: ["$sessionId", "$$id"]
                                }
                            }
                        }
                    ],
                    as: "unreadcounts"
                }
            }
    

  2. 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 the sessionId from the UnreadCount collection to ObjectId.

    {
      $lookup: {
        from: "UnreadCount",
        let: {
          sessionId: "$_id"
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: [
                  "$$sessionId",
                  {
                    $toObjectId: "$sessionId"
                  }
                ]
              }
            }
          }
        ],
        as: "unreadCounts"
      }
    }
    

    Or you can convert the _id from the Session collection as string type.

    {
      $lookup: {
        from: "UnreadCount",
        let: {
          sessionId: { $toString: "$_id" }
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: [
                  "$$sessionId",
                  "$sessionId"
                ]
              }
            }
          }
        ],
        as: "unreadCounts"
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search