collection is not defined in mongodb

Here your not declared the variable(collection) so that only you got this error.You need to declare that variable with proper collection name.

For Example :
If you are going to find the records in users collection under test schema you need to the follow the below code.

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/test";
var collection = null;
MongoClient.connect(url, function(err, db) {
  if(!err) {
    console.log("We are connected");
    collection = db.collection('users');
 }});
        exports.getprofile = function (url,req, res) {
    collection.find({}).toArray(function(err,res, docs) {
    if(err){
      res.send(err);
    }else if(res.length){
      console.log(res)
      }
      else{
        console.log('no docs found');
      }
    res.send(res);
  });
}

Note : You Need Some Records in users collection under test schema.

Leave a Comment