Getting the most recent record

3,318 views
Skip to first unread message

James Carr

unread,
Jun 22, 2011, 11:41:27 PM6/22/11
to mongoo...@googlegroups.com
Hi All,

I'm new to mongoose and unfortunately I couldn't find any examples in
the documentation to get the most recent object from the datastore.
Basically I want to be able to pull a Lead with the most recent
arrival date.

I found a lot of examples on the mailing list but sadly none of them
seem to work.

Basically I have a database of Lead documents with an arrival Date
property. I want to get the one with the most recent arrival date.

From the mailing list I found this:


Post.findOne({}, [], { $orderby : { 'created_at' : -1 } },
function(err, post) {
console.log(post.title);
}


But that doesn't seem to work (it gives me the one with the oldest
arrival date). I changed the negative 1 to a positive but still no
dice.

If someone could please help or even point me in a direction to RTFM
I'll be thankful. ;)

Thanks,
James

James Carr

unread,
Jun 22, 2011, 11:57:08 PM6/22/11
to mongoo...@googlegroups.com
Hi,

I tried this which gave me documents sorted in with the newest first:

Lead.find({}, [], {sort:[['arrival',-1]]}, this.callback);

Sadly, when I try to run this as findOne I dont get the most recent.

Thanks,
James

dudley ackerman

unread,
Jun 23, 2011, 12:51:49 AM6/23/11
to mongoo...@googlegroups.com
i see this post - and so you would limit(1) after sort:

you seem to need to call find() again on the actual Query object which is returned on the find call (plus watching out for your err object). So:-

  Item.find().sort('_id','descending').limit(15).find(function(err, doc) {
    client
.send(JSON.stringify(doc));
Reply all
Reply to author
Forward
0 new messages