简体   繁体   中英

Fetching last record from mongodb using node.js

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.

limit不带回调参数,因此您必须调用exec才能实际执行查询。

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

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);
  },
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM