Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

How to find a latest data in array in mongoose


I have a conversation model like below:

const ConvoSchema = mongoose.Schema({
    convoId: {
        type: String,
        required: true
    },
    seller: {
        type: String,
        required: true
    },
    buyer: {
        type: String,
        require: true
    },
    product: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
    messages: [{ type: Schema.Types.ObjectId, ref: 'Message' }]
})

and I'm trying to get latest message in the Convo but couldn't figure out how to do it. any ideas?


Solution

  • _id basically contains the timestamp in it, so the first element that you get in .find() will be the oldest and the last element will be newest,

    so by adding a sort like: { _id: -1} will give u the latest data

    var Convo = mongoose.model('Convo', ConvoSchema); //init mongoose model
    
    Convo.find()
         .limit(1)
         .sort({ _id: -1 })
    

    you can remove the .limit() if u want complete list of documents

    =======================================================================

    Sorry for not reading it properly,

    For Latest message,

    Convo.findOne({}, response => {
       var data = response.toObject();
       latestMessage = data.messages.pop()
    })