Makizh
Makizh

Reputation: 189

How to get last record's one value in mongoose

Tried to get last record value one but not working. How to do it in mongoose.

Sample data records in mongodb:

[
    {
        _id: 5f0c73f69b34214310d0acee,
        name: "Test",
        age: 28,
        voice: "Not Tested"
    },
    {
        _id: 5f0c73f69b34214310d0akke,
        name: "Test2",
        age: 38,
        voice: "Tested"
    }
]

Mongoose query:

The value of voice property in the last record is "Tested" so I tried to get that value.

var Order = mongoose.model(collectionName);
  Order.find({}).sort({ _id: -1 }).limit(1).then((products) => {
    
    products.findOne({voice}, function(err,obj) { 
    
      console.log(obj);//Output should be = Tested
    
    });
});

Upvotes: 3

Views: 8113

Answers (3)

Mehedi
Mehedi

Reputation: 559

I found it simpler this way.

let lastDoc = (await Model.find({}).sort({_id: -1}).limit(1))[0];
console.log(lastDoc);

Otherwise, if you use it inside a function, make sure the function is async.

let docHandler = async () => {
   let lastDoc = (await Model.find({}).sort({_id: -1}).limit(1))[0];
   console.log(lastDoc);
};

Upvotes: 0

Nithin K Joy
Nithin K Joy

Reputation: 963

Finally, after trying for long 3 hours I found the answer.

    User.find({}).sort({_id: -1}).limit(1).then((products) => {
        console.log(products[0].voice)
    })

Upvotes: 10

AlexZeDim
AlexZeDim

Reputation: 4352

Because you doing it wrong. Actually if you needed not last inserted in a collection document, but last updated you should use timestamps in your schema (mongoose docs)

So you collection schema should be something like this:

let schema = new mongoose.Schema({
    field_one: Number,
    field_two: String,
},{
    timestamps: true
});

So you will have not just field_one and field_two, but also special fields like createdAt and updatedAt

Then, don't forget to add index for performance at you schema on updatedAt field, like this:

schema.index({ updatedAt: -1 },{name: 'IndexName'});

and only them use:

async function LastUpdatedVoice () {
   try {
       let t = await model.findOne({ "field_one": "value" }).select('voice').lean().sort({updatedAt: -1});
       console.log(t);
   } catch (e) {
       console.error(e)
   }
}

For last inserted document the code will be the same, but instead of updatedAt field, you should use createdAt field.

Also, one more thing:

*If you need to updated this document right after it has been found, you could do it without using lean() option in my query. And updated the Mongoose Doc itself, via:

t.voice = new_value
t.save()

but I highly recommend you to use findOneAndUpdate method them.

Upvotes: 2

Related Questions