0

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

3 Answers 3

1

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


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

1 Comment

Thank you very much. I added this to my code. But There was no error. So I reinstalled everything(node, MongoDB, etc). Now It's working. I don't understand what was the exact error. Now It's solved. Thanks again
0

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

1 Comment

Thank you very much for helping me. everything is ok now. I reinstalled the node and Mongo DB again. It seems like the error was not in the code. It was something else.
0

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

1 Comment

I couldn't find an error. Then I reinstalled Node and Mongo DB. Then the problem solved. I have no Idea What was the exact error. But Thank you for the help.

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.