codingsplash
codingsplash

Reputation: 5045

Unable to retrieve data from MongoDB in Express

I am trying to write a simple code to fetch some data from MongoDB in express. Below is my code:

var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/mcart'
MongoClient.connect(url)
    .then(function (db) { 
        console.log(db)
    })
    .catch(function (err) {})

This gives me a JSON. But, when I try to access data from it, I get an error "db.collection" is not a function

var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/mcart'
MongoClient.connect(url)
    .then(function (db) { 

        var cursor=db.collection("product_catalog").find();
        cursor.each(function(err, doc) {
            console.log(doc);
        });
    })
    .catch(function (err) {console.log(err)})

Where am I going wrong?

Upvotes: 1

Views: 526

Answers (3)

codingsplash
codingsplash

Reputation: 5045

I tried the below code and this is working fine. This code is basically a combination of the other two answers. Just posting it for others in future.

var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017'
var databaseName="mcart";

MongoClient.connect(url)
    .then(function (mongoClientInstance) {     
        var database = mongoClientInstance.db(databaseName);
        var x=database.collection("product_catalog").find().toArray();
        return x; 
    })
    .then(x=>console.log(x))
    .catch(err=>console.log(err))

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 10148

As you are using ^3.0.x this is the way to connect and execute queries.

Using MongoDB nodejs driver with version ^3.0.x gives you client object as callback function argument.

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  if(err)
     throw err
 // Client returned
 var db = client.db('mcart');
 db.collection("product_catalog").find();
 ...
});

The way you're doing is the old way, used in 2.x version where it gives you db object as an argument to the callback function.

Read more about the change logs here

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Use hasNext(). It will move to the next doc in the cursor until it reaches to the end. Also get the database name before querying the collection

var DbName = db.db("databaseNameHere");
var cursor = DbName.collection("product_catalog").find();

while (cursor.hasNext()) {
   console.log(tojson(cursor.next()));
}

Change your code to:

var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/mcart'
MongoClient.connect(url)
.then(function (db) { 
    console.log("Before")
    var DbName = db.db("databaseNameHere");
    var cursor=DbName.collection("product_catalog").find();
    while (cursor.hasNext()) {
      console.log(tojson(cursor.next()));
    }
    console.log("after")
})
.catch(function (err) {})

Upvotes: 2

Related Questions