Daniel_Madain
Daniel_Madain

Reputation: 491

MongoDB find returning zero results

I know this will be something small I'm missing, but would appreciate the help.

Here is my test script (node.js)


var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/myTestDB',
    function (err, db) {
        if (err)
            debugger;
        else {            
            db.collection('test', function (err, collection) {

                collection.save({ name: "danny" }, function () { debugger;});

                collection.find(function (err, results) {
                    if(results.items.length == 0){
                       ///======> always = 0 !!!! WHY?!!!!
                        debugger;
                    }
                });
            });

        }
        db.close();
    });

feel free to start your answer with "duh!"

Upvotes: 1

Views: 403

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312095

UPDATE: you also need to move your db.close(); call inside the find callback or you're closing the connection before you're done with it.

In your example, results is a cursor, not an array of docs, so you need to call toArray on it to iterate over the cursor and get the array of docs. But you also need to put your find call inside the save callback. Otherwise the find is executing before the save has completed.

So something like this instead:

collection.save({ name: "danny" }, function () {
    collection.find().toArray(function (err, results) {
        // results contains the array of docs

        // Now you can close the connection.
        db.close();
    });
});

Upvotes: 2

Related Questions