30
loading...
This website collects cookies to deliver better user experience
mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<db-name>?retryWrites=true&w=majority
. The username, cluster-name and db-name fields will be automatically filled out.npm install
to install Express, the only dependency.app.js
file should look like this.// app.js
const express = require("express");
const port = 3000;
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Your app is listening on port ${port}`);
});
node app.js
and you should see the confirmation message that your app is listening on a particular port.npm install dotenv
..env
file in the root of your project, paste in your URI, and assign it to a DB_URI
variable. Make sure your version includes your password as well as your username, cluster name and database name.// .env
DB_URI=mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<db-name>?retryWrites=true&w=majority
db.js
file. This will contain all the configuration for connecting to your database.npm install mongoose
and import it into db.js
.db
from process.env.DB_URI
.connectDB
function. Make sure you mark it as an async
function as it will take some amount of time to connect to your database.connectDB
, create a try-catch
block to handle any errors that occur.try
block, await mongoose.connect()
. Pass it the db
variable and a settings object. In the settings object, set useNewUrlParser
and useUnifiedTopology
to true
. This will prevent Mongoose from giving you warnings. Mongoose explains the warnings in their documentation.console.log
a success message to tell you you've connected to your database. I once spent an hour trying to debug a database connection simply because I wasn't telling myself it was connected.catch
block, console.error
any error you receive and use process.exit(1)
to terminate the process if an error occurs.connectDB
function.db.js
file should now look like this.// db.js
const mongoose = require("mongoose");
const db = process.env.DB_URI;
async function connectDB() {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connected");
} catch (error) {
console.error(error.message);
process.exit(1);
}
}
module.exports = connectDB;
app.js
file, require dotenv
and call the config
method on it.connectDB
function and call it.// app.js
require("dotenv").config();
const express = require("express");
const connectDB = require("./db");
const port = 3000;
// Connect to database
connectDB();
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Your app is listening on port ${port}`);
});
node app.js
, you'll see two messages printed to your console: that your app is running and that you've connected to your database. From here you can start to write schemas and perform CRUD operations with your data.