skip to Main Content

I was building a chat server, where i need to get the number of messages that is not marked as
seen . below is my schema

const ChatSchema = mongoose.Schema({
    chatId: { type: String, required: true, unique: true },
    messages: [
        {
            message: { type: String, required: true },
            sendBy: { type: String, required: true },
            sendTo: { type: String, required: true },
            seen: { type: Boolean, default: false },
            date: { type: Date, default: Date.now()}
        },
    ],

})

I have tried the following code but it always returns 1

const unSeenCount=await Chat.find({ chatId: chatId }, 
            { messages : { $elemMatch : { seen : false } } })
        
        console.log(`unseen count is ${unSeenCount.length}`);

2

Answers


  1. The first object in the mongoose query is the filter which is what you were using in the second object. You can also use count to get the count returned by the filter query.

    Try this:

    const unSeenCount = await Chat.count({
        messages: {
            $elemMatch: {
                seen: false
            }
        }
    })
    
    console.log(`unseen count is ${unSeenCount}`);
    
    Login or Signup to reply.
  2. you can use the countDocuments Method

    const unSeenCount=await Chat.countDocuments({{ chatId: chatId }, 
            { messages : { $elemMatch : { seen : false } } }})
        
        console.log(`unseen count is ${unSeenCount}`);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search