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}`);
CodePudding user response:
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}`);
CodePudding user response:
you can use the countDocuments Method
const unSeenCount=await Chat.countDocuments({{ chatId: chatId },
{ messages : { $elemMatch : { seen : false } } }})
console.log(`unseen count is ${unSeenCount}`);