ZiTAL
ZiTAL

Reputation: 3581

nodejs get find results in mongodb

I'm trying to get the result of query but i get the same info in all vars: db, collection and res:

var mongodb = require("mongodb");
var mongoserver = new mongodb.Server("localhost", 27017);
var instance = new mongodb.Db("test", mongoserver);

instance.open(function(err, db)
{
  console.log('db:');
  console.log(db);
  db.collection('kurtsoa', function(err, collection)
  {
    console.log('collection:');
    console.log(collection);
    collection.find({}, function(err, res)
    {
      console.log('res:');
      console.log(res);
    });
  });
});

how i can get the result of "find"?

Upvotes: 2

Views: 11123

Answers (2)

TaLha Khan
TaLha Khan

Reputation: 2433

You can use this:

 collection.find().toArray(function(err, docs){
                console.log(docs);
    )};

Upvotes: 2

Chad
Chad

Reputation: 19609

.find() will return a Cursor object for you to work with. If all you are interested in is getting all the results in an array you can do:

collection.find().toArray(function(err, docs) {
    console.log(docs);
});

But you can also iterate the cursor too:

collection.find().each(function(err, doc) {
    //called once for each doc returned
});

Upvotes: 21

Related Questions