4

Model:

const Room = new Schema({
  topic: String,
  messages: [{
    text: String,
    readByUsers: [String] // Array of users Ids, which read this message
  }]
});

Example data:

{
  topic: 'First',
  messages: [
{
      text: 'First message',
      readByUsers: ['id1', 'id3', 'id2']
    },
    {
      text: 'Second message',
      readByUsers: ['id1', 'id2'] //id3 not read this
    }
  ]
},
{
  topic: 'Second',
  messages: [
    {
      text: 'Third message',
      readByUsers: ['id1', 'id3', 'id2']
    },
    {
      text: 'Fourth message',
      readByUsers: ['id1', 'id2', 'id3']
    }
  ]
}

My goal - receive First object, because Second message was not been read by id3 user (this key not exists in readByUsers array).

Query like: Search all documents, where some of messages.readByUsers not contains specific userId

Model.find(messages.readByUsers: {$nin: [userId]})

works only if no one of messages.readByUsers not contains id, for example Model.find(messages.readByUsers: {$nin: ['id4']}) - returns both objects

1 Answer 1

3

You can do this by using the $elemMatch operator which looks for at least one element which satisfies its conditions:

Model.find({messages: {$elemMatch: {readByUsers: {$ne: 'id3'}}}})
Sign up to request clarification or add additional context in comments.

Comments

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.