bafrick bafrick - 5 months ago 11
Node.js Question

Get a given field from the most recent document in MongoDB

I am trying to get the _id field of the most recent document entered into the collection.

I have created a collection called Rooms:

Rooms = new Meteor.Collection('rooms');


and this code should get the most recent item limited to one:

Rooms.find({}, {fields: {'_id':1}}).sort({_id:-1}).limit(1)


instead, I get

Uncaught TypeError: Rooms.find(...).sort is not a function(…)


Where am I going wrong?

Solution (thanks @aedm)




var roomID = Rooms.findOne({}, {fields: {_id: 1}, sort: {_id: -1}});
return roomID._id.toString();

Answer

Collection.find returns a cursor, not an array. Cursors don't have a sort method. Try the following instead:

Rooms.findOne({}, {fields: {_id: 1}, sort: {_id: -1}});

http://docs.meteor.com/api/collections.html#Mongo-Collection-find