1

I am trying to fetch last record from mongodb database using node.js. I found some answer from here. Now i have given query like

Videopost.find({}).sort({_id:-1}).limit(10,function(err,docs){}

Trying to print docs in console but couldn't get any value in docs.

1
  • How are you printing the docs? Commented Dec 5, 2015 at 12:40

2 Answers 2

3

limit doesn't take a callback parameter, so you have to call exec to actually execute the query.

Videopost.find({}).sort({_id:-1}).limit(10).exec(function(err,docs) {...});
Sign up to request clarification or add additional context in comments.

Comments

1

In case somebody is looking for the answer for node.js, you can use findOne() function. This worked for me:

db.collection('collectionName').findOne(
  {},
  { sort: { _id: -1 } },
  (err, data) => {
     console.log(data);
  },
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.