1

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?

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50

2 Answers2

1

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');
};
  • I donot want to establish a new connection in myAnotherModule; I have already got the connection established in myModule; Why is mongoose not being shared in myAnotherModule? Am I required to do anything else, which I am missing ? – user3782548 Sep 07 '17 at 13:10
0

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);
   });
  • I think I did not make my issue clear; I shall try again. – user3782548 Sep 08 '17 at 00:49
  • I think I did not make my issue clear; I shall try again. I have a main module. Main module has routers, services, models. It has a mongoose connection established. I have added another package, moduleB; ModuleB also has routers, services, models. I have "npm link"ed moduleB in my main module. In moduleB, I am facing this issue of not getting access of mongoose related information. I tried what you have suggested in moduleB, still same problem; Once npm linked, is not moduleB part of main module? then why is it not gettinng mongoose object? – user3782548 Sep 08 '17 at 00:59
  • 1
    Did you find the solution for this? – Bikash Gupta Jul 05 '18 at 15:50