Reputation: 23
I'm trying to create a mongo DB database with node js. I have installed MongoDB community server 4.4 in my computer. I can do CRUD operations directly from the console. But when I try to connect it to my app It does not work. There is no error message in the console. My code as follows.
const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const mongoose = require('mongoose')
const app = express()
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB", {useNewUrlParser: true, useUnifiedTopology: true})
app.listen(3000, function(){
console.log("Server started on port 3000");
});
Upvotes: 0
Views: 467
Reputation: 46
try this Create a database called "mydb":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Upvotes: 0
Reputation: 73
As per your question your code looks fine and on console i don't see any error but as you are saying your database is not connecting you can put your code in try catch method
try {
mongoose.connect("mongodb://localhost:27017/wikiDB", {useNewUrlParser: true,useUnifiedTopology: true})
console.log( "Database Connected Successfully")
} catch (error) {
console.error(error);
}
it will show you the error
Upvotes: 0
Reputation: 513
Change the mongoose.connect()
like below :
mongoose.connect("mongodb://localhost:27017/wikiDB", {
useNewUrlParser: true,
useUnifiedTopology: true
}, function(error) {
if (error) {
console.log(error.message);
} else {
console.log("Successfully connected to database.");
}
})
Upvotes: 1