collection is not defined in mongodb

By : nlr_p
Source: Stackoverflow.com
Question!

I am trying to get results from mongodb collection but when i call the function through routes it says the error collection is not defined,can any one suggest me help,

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
  if(!err) {
    console.log("We are connected");

 }});

  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);
  });
}
By : nlr_p


Answers

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.



You have to get the collection object first as mentioned below

  var collection = db.collection("simple_document_insert_collection_no_safe");

// Insert a single document collection.insert({hello:'world_no_safe'});

Please refer the below link for more details.

mongod db collection using nodejs



I think you could rewrite this as a single query on the status table, using ORs to test each scenario, like so:

SELECT ss.int_tran_id
FROM   status SS
WHERE  ss.stage in ('ACHPayment_Confirmed', 'HIFV4', 'HIFV5_FTRINF', 'Payment_HIFV5_FTRINF')
OR     (ss.stage = 'PREVDAY'
        AND (EXISTS (SELECT NULL
                     FROM   references rf
                     WHERE  ss.int_tran_id = rf.int_tran_id
                     AND    rf.mid_ref IS NOT NULL)
             OR EXISTS (SELECT NULL
                        FROM   app_data ad
                               INNER JOIN ach aa
                                 ON (ad.app_data_id = aa.ach_id)
                        WHERE  ss.int_tran_id = ad.int_tran_id
                        AND    aa.par_number IS NOT NULL)));
By : Boneist


This video can help you solving your question :)
By: admin