gravetii
gravetii

Reputation: 9624

Get the correct result while executing a find query on mongodb using node

So I am trying to run a nodejs script to make some custom action on a mongo database. The problem I am facing is with the following script -

            // a valid id obtained before
            collection.find({"id":id}, function(err, result) {
                if(err) {
                    console.log("Could not select");
                } else {
                    console.log("Select successful for id: " + id);
                    console.log(result);
                }
            });

Now when I check the result after running this, I only see data about the db, a whole lot of it that is not really concerned with the select query. What I want is what anyone would expect! A list of the documents for that id. Obviously, I am missing something here, could anyone please point me to it?

EDIT:

So when I run the query on the mongo shell, I get the expected result.

db.messages.findOne({"id":"<a random id that has a json inserted in mongo>"})

However, when I run it from the script shown above, all I get is this:

Select successful for id: <random uid from above>

{ db: 
   { domain: null,
     _events: {},
     _maxListeners: 10,
     databaseName: 'test',
     serverConfig: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _callBackStore: [Object],
        _commandsStore: [Object],
        auth: [Object],
        _dbStore: [Object],
        options: [Object],
        _serverState: 'connected',
        _haProcess: [Object],
        servers: [Object],
        strategyInstance: [Object],
        emitOpen: false,
        .....
        .....
        .....

Thanks

Upvotes: 0

Views: 76

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

The result parameter that find provides to the callback is a cursor, not an array of results. Call toArray to iterate over the resulting cursor and get an array of docs:

collection.find({"id":id}).toArray(function(err, result) {
    if(err) {
        console.log("Could not select");
    } else {
        console.log("Select successful for id: " + id);
        console.log(result);
    }
});

Or if id uniquely identifies a single doc, use findOne instead:

collection.findOne({"id":id}, function(err, result) {
    if(err) {
        console.log("Could not select");
    } else {
        console.log("Select successful for id: " + id);
        console.log(result);
    }
});

Upvotes: 2

Related Questions