Setting Up a Node.js Project
Initialize Node.js Project: Create a new folder for your project and run npm init to initialize a new Node.js project.
Install Dependencies
npm install express mongoose
Connecting MongoDB with Mongoose
Set up a basic Express application in your index.js file:
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
require("./dbconnection.js")
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Set up a Db connection file dbconnection.js file:
const mongoose = require("mongoose");
const express = require("express");
require("dotenv").config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", process.env.MONGODB_URI);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
by replacing process.env.MONGODB_URI with you own url
Go to terminal and type npm start
npm start
Congratulatios! you db has been connected now you can start playaround it
Top comments (0)