Reputation: 17
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.
Upvotes: 0
Views: 4368
Reputation: 1
const config = require('../config');
const Mongoose = require('mongoose');
Mongoose.connect(config.dbURI);
Mongoose.connection.once('open',()=>{
console.log('Connected to db');
});
it helps me.
Upvotes: 0
Reputation: 319
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
Upvotes: 1
Reputation: 871
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.
Upvotes: 0
Reputation: 11
Try this:
const mongoose = require('mongoose');
mongoose.connect(mongoURI);
mongoose.connection.once('open',()=>{
console.log('Connected to db');
});
Upvotes: 0