Dirk Dirk - 1 year ago 72
Javascript Question

Get the first element of a Mongo cursor

I can iterate through all the elements of a cursor (up to the number returned) using:

cursor.each(function(err, doc)

But how to I just get the first element from the cursor?


It's terribly inefficiently to call toArray if you just want the first doc of the results. Instead, call next on the cursor:

cursor.next(function(err, doc) {
    if (doc) {

Another option is to just call findOne instead of find if you only want a single doc anyway.