Grouping documents in mongoose

Viewed 21

I am building a chat app using nodejs and mongoose. I need to retrieve chats for a user(logged in user) such that the retrieved data/chats will contain the latest message and the name of the user the logged in user had a chat with. I am not able to come app with a way to aggregate the data since the sender can also be a recipient in a chat. My message schema is shown below.

const messageSchema = new mongoose.Schema(
  {
    content: { type: String, required: true },
    fromUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    toUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    users: Array,
    messageRead: { type: Boolean, default: false },
  },
  {
    timestamps: true,
  }
);

The purpose of this is to have a list of chats render on the front end which when clicked will open an inbox containing messages between the two users.

1 Answers

You can just use the $or operator. This way it will return all elements where the user is the sender or recipient:

.aggregate([
  {
    $match: {
      $or: [
        {
          fromUser: ObjectId("<UserID>")
        },
        {
          toUser: ObjectId("<UserID>")
        }
      ]
    }
  }
 // additional aggregate steps like sorting by createdAt and limiting output
])
Related