2
var cursor = db.collection('Carreer').find();
cursor.each(function (err, results) {
    // the last results call is null
});

This loop seems to run one extra time, returning null as the last value for every column in the table. How do I stop cursor.each from returning the null value?

2
  • Try toArray and check log, how many array elements are there, db.collection('Carreer').find().toArray(function (err, result) { if (err) throw err console.log(result) }) Commented Jul 6, 2018 at 12:29
  • are you using mongoshell or node ? Commented Jul 6, 2018 at 13:42

1 Answer 1

5

This is the expected behaviour of cursor.each. The null value indicates there are no more results (ie the cursor is exhausted/empty and closed). If you don't want the extra null call when the cursor is finished, you can use cursor.forEach:

db.collection('Carreer').find().forEach(function(doc) {
  // handle
}, function(err) {
  // done or error
});

Also note:

cursor.each is deprecated.

Why the null?

The cursor.each method just has one callback and the only way to know the cursor has finished is the last null. An example implementation could be:

function fetchAllCareers(callback) {
    const results = [];
    const cursor = db.collection('Carreer').find();
    cursor.each(function(error, result) {
        if (error) {
            callback(error);
            return;
        }
        if (result === null) { // This was the last iteration, we finished
            callback(null, results);
            return;
        }
        results.push(result);
    });
}

The cursor.forEach method on the other hand has an an iterator callback and a second callback to let you know that the iterations have finished. An example implementation could be:

function fetchAllCareers(callback) {
    const results = [];
    const cursor = db.collection('Carreer').find();
    cursor.forEach(function(result) {
        results.push(result);
    }, function(error) { // all iterations finished
        callback(error, results);
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yea it worked... I dont understand why forEach End At last data while each keep running one time extra any logical explanation to this..
They just work differently, cursor.each just has one callback and the final null lets you know the iterations have finished and you can do your final logic when you receive the null. cursor.forEach on the other hand, has an iterator callback and a second finish callback which lets you know the iterations have finished.

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.