Node.js - Mongoose not accessing DB in included package

179 views Asked by At

I have started working of late on MEAN technologies;

I have a module myModule. It has routes, services, models accessing database.

I have created another project, myAnotherModule in a separate directory, and have "npm link" ed it into myModule. While I try to use Mongoose in myAnotherModule, it is unable to access DB with proper credentials.

In the following code in myAnotherModule,

var db  = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new grid(db, mongoDriver);

it does not find the mongoose.connection.db and db is undefined. Whereas if I use these lines in myModule, then the code works fine.

Why is myAnotherModule not able to find mongoose.connection.db? How does npm link work?

2

There are 2 answers

1
Krishan Kant Sharma On

Try to connect following way :

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

exports.test = function(req,res) {
  res.render('test');
};
3
AudioBubble On

I happened to encounter this issues recently as well. Typically people separate db config thus cause this problem. Try to declare in proper block that ensures mongodb is already connected.

  db.once('open', function callback () {
        var gfs = new grid(mongoose.connection.db, mongoDriver);
   });