Tharindu Dhanushka
Tharindu Dhanushka

Reputation: 23

Cannot create or connect to local Mongo DB with Node

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");
});

This is my console

Upvotes: 0

Views: 467

Answers (3)

Vikram choudhary
Vikram choudhary

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

Shubham Digole
Shubham Digole

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

Dhaval Darji
Dhaval Darji

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

Related Questions