Search code examples
javascriptnode.jsmongodbmongoosemongodb-query

Fetch the latest data using date in mongodb


I am trying to fetch the latest data from MongoDB in nodejs. let me explain with an example every 2hours I am uploading the data to a collection. when I do a get method I need the latest data how do I do that.

Please help me with this issue.

Here is the Schema
var abc = new mongoose.Schema({
    ItemName : String,
    date:   Date
         ......
});
This is how I am storing 

finalData.push({
                ItemName: xyz,
                date: new Date()})

abc.insertMany(finalData)

Solution

  • try like this:

    your_model_name.find({}).sort('-date').exec(function(err, docs) { ... });