8
exports.c_39 = function(req,res) {
    var mongoose = require('mongoose');
    mongoose.createConnection('mongodb://localhost/cj');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    console.log('a')
    db.once('open',function(){
        console.log('b')
    })
}

Can perform the console.log (' a '), but cannot perform DB.once ('open') callback function

3 Answers 3

13

That's because mongoose.connection isn't the same as the connection that is returned by createConnection().

There are two ways of opening a connection with Mongoose:

// method 1: this sets 'mongoose.connection'
> var client = mongoose.connect('mongodb://localhost/test');
> console.log(client.connection === mongoose.connection)
true

// method 2: this *doesn't* set 'mongoose.connection'
> var connection = mongoose.createConnection('mongodb://localhost/test');
> console.log(client.connection === mongoose.connection)
false

So to solve your problem, you need to connect your event handler to the connection as returned by createConnection(), and not to mongoose.connection:

var db = mongoose.createConnection('mongodb://localhost/cj');
db.once('open', function() { ... });

In short:

  • .createConnection() returns a Connection instance
  • .connect() returns the global mongoose instance
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please tell me what is the difference between once and on in mongoose.connection.
@Alexander once will call the provided callback only one time, for the first open event that happens; on will call the provided callback each time an open event occurs. See also the events documentation for Node.js
1

Instead of mongoose.createConnection use: mongoose.connect('mongodb://localhost/cj');

Comments

0

do

db=  mongoose.createConnection('mongodb://localhost/cj'). 

Then use

db.on("connected", connected); with connected = err => {
  console.log(`connected ${db.readyState}`);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.