0

I am dealing with an issue while querying a notification schema

receiver: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Profile' }],
readBy: [{
    readerId: { type: mongoose.Schema.Types.ObjectId, 
                ref: 'Profile', default: [] },
    readAt: { type: Date }
  }]

In order to query latest notifications, this is the query I have written:

GOAL is to check if the "profile.id" DOES NOT exist in the readBy array (which means its unread by that user)

const notifications = await Notification.find({
      receiver: profile.id,    // this works 
      readBy: {                // but, adding this returns an empty array 
        $elemMatch: {
          readerId: { $ne: profile.id }
        }
      }
})

Would really appreciate the help, stuck here for days.

1 Answer 1

2

I think is easier than we are trying to do.

If you want to know if the element is into the array, then, query looking for it. If the query is empty, it implies that not exists, otherwise yes.

Look this example.

Is a simple query, only check if one document has been received and readed by user profile.id.

db.collection.find([
  {
    "receiver": profile.id,
    "readBy.readerId": profile.id
  }
])

Please check if the output is as expected or I misunderstood your petition.

In mongoose you can use this:

var find = await model.find({"receiver":1,"readBy.readerId":1}).countDocuments()

It will return how many documents match the query.

Edit to get documents where readerId is not present in the array:

Here, you only need to add $ne operator

db.collection.find([
  {
    "receiver": profile.id,
    "readBy.readerId": {
      "$ne": profile.id
    }
  }
])

You can check this here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but there is one important thing you missed here, I want readerId NOT to be present in the readBy array. Could you update the answer for that?
Thanks alot, it worked and the mongo playground was something I wasn't aware of. Its amazing and really helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.