Search code examples
node.jsmongodbmongoosepopulate

Mongoose - How to populate only the first element in a nested array of every object


I am trying to create a Chat App in NodeJS, Mongoose and React Native and I want to show to the user the last message of every conversation.

I have an array of messages in my Conversation Schema as following:

const ConversationSchema = new mongoose.Schema({
    {...}
    messages: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Message'
        }
    ]
    {...}
})

I wonder if anyone can help me to be able to only populate the first message of every Conversation so the response will be:

conversations: [
    {
        "_id": ObjectId(...)
        "messages": [
             "text": "Last message"
        ]
    },
    {
        "_id": ObjectId(...)
        "messages": [
             "text": "Last message"
        ]
    },
    ...
]

I am currently using the populate function of mongoose but the problem is that if only populates the first conversation:

Conversation.find().populate(query).exec((err, conversations => {
    {...}
})

const query = {
    {
        path: "messages",
        options: {
            limit: 1,
            sort: { _id: -1 }
        }
    }

}

Note: If I do not specify the limit: 1 and sort: { _id: -1 } it correctly populates all elements of the array but that's not what I am looking for.

Thanks to anyone who can help me!


Solution

  • You need to use perDocumentLimit than Limit

    If you need the correct limit, you should use the perDocumentLimit option (new in Mongoose 5.9.0). Just keep in mind that populate() will execute a separate query for each story, which may cause populate() to be slowe