Search code examples
node.jsmongodbexpressmongoosemongoose-schema

Mongoose - query doc if element not in array


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.


Solution

  • 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