Terminal
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(node:16036) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
server is running on 5000
db error
this is index.js
const express = require('express');
const app = express();
var mongoUrl ="mongodb://localhost:27017/TestDB"
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/TestDB", { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
if (!err) console.log('db connected');
else console.log('db error');
})
app.listen(5000, () => {
console.log('server is running on 5000');
});
CodePudding user response:
mongoose
.connect(`mongodb srv://DB_USER:[email protected]/myFirstDatabase?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Database connection successful!');
}).catch(error){
console.log(error)
}
you can get the entire connection string from MongoDB and input your DB user and password
CodePudding user response:
It seems that you are trying to connect to a local instance of MongoDB. I remember this caused me a few headaches.
Try making sure that you have it downloaded and running:
- Open command prompt (on Windows) or terminal (on MacOS)
- Type
mongod
and click enter
If you get a long response then you have it installed but it might not be running or running on the correct port.
If you get a response something like this: 'mongod' is not recognized as an internal or external command, operable program or batch file.
then that means you don't have MongoDB installed https://www.mongodb.com/docs/manual/administration/install-community/ to find instructions on how to install it.
Also... The code you are using would work but it's a little untidy.
Try:
const express = require("express")
const mongoose = require("mongoose")
const app = express()
// Define port and mongodb url once so you don't have to repeat yourself
const PORT = 3000
const MONGO = "mongodb://localhost:27017/TestDB"
// Add this line to get rid of the first error you got
mongoose.set("strictQuery", false)
mongoose
.connect(MONGO, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Database connected!"))
.catch((err) => console.log(err))
app.listen(PORT, () => {
console.log("Server is running on port " PORT)
})