0

I am getting an error when i run my application.

The error:

 MongoDB.on('error', function(err) { console.log(err.message); });
 TypeError: Cannot read property 'on' of undefined
 ...

I tried to comment that part of the code out to see if i have anymore similar errors and found another same one. ( This time the word "once" )

The code:

var mongoURI = "mongodb://localhost/chatapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
    console.log("mongodb connection open");
});

It would be really great if anyone could help me solve this :( I searched the internet and found nothing helpful.

4 Answers 4

1
var mongoose = require('mongoose');
var mongoURI = "mongodb://localhost/chatapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
    console.log("mongodb connection open");
});

also before running the application in your terminal type npm install mongoose --save

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

   const mongoose = require('mongoose');

    mongoose.connect(mongoURI);
    mongoose.connection.once('open',()=>{
        console.log('Connected to db');
    });

3 Comments

Now it just says that "mongoURI is not defined"
Is your local database running when your are executing the code.
If you have'nt installed mongodb locally then you can refer to mlab, It is a kind of online mongodb, you will be provided with the mongoURI. Check it out on how to use it
0

The message is pretty clear. MongoDb is undefined.

Speaking on your MongoDb variable. Should be mongoDb with lowercase. It is one instance.

Anyway, the problem is in mongoose.connect(mongoURI).connection. Debug from there.

Comments

0
const config = require('../config');
const Mongoose = require('mongoose');

Mongoose.connect(config.dbURI);
Mongoose.connection.once('open',()=>{
    console.log('Connected to db');
});

it helps me.

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.