PermalinkNode and typescript Modules Setup
PermalinkInitial setup of node server in order to install npm packages npm has to be initailized.
cd server
npm init -y
installing necessary database, express backend dotenv cors dependencies in normal mode.
npm i express node cors dotenv mongo
For development mode installing necessary
npm i -D ts-node-dev typescript nodeman @types/cors @types/express @types/node
npm install typescript@latest @types/mongoose@latest --save-dev
Create ".env" file in the server folder i.e root folder of the server in order to access the names by processor to connect using environmental variables or else it throws error in DB
Error connecting to database MongooseError: The `uri` parameter to
`openUri()` must be a string, got "undefined". Make sure the first
parameter to `mongoose.connect()` or `mongoose.createConnection()`
is a string.
PermalinkMongoDB connection
// src/config/db.ts
import mongoose from "mongoose";
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI!)
} catch (error) {
console.log("Error connecting to database", error);
}
const connection = mongoose.connection;
if (connection.readyState >= 1) {
console.log("Connected to Database!")
return;
}
connection.on("error", () => console.log("connection failed"));
};
export default connectDB;
How your mongoose Database looks after creating the schema and model of the data to be present.
PermalinkExpress Setup
The index.ts file must have express to connect to backend, cors to enable frontend connection,
dotenv to access the variables in .env file of the server / root directory of backend code.
import cors from 'cors';
import dotenv from "dotenv";
import express, { Express } from "express";
import connectDB from './config/db';
import router from './routes/dashboardRoutes';
/**
* Create an Express application anf get the
* value of the PORT environmental variable
* from the `process.env`
*/
const app: Express = express();
const PORT = process.env.PORT || 4000;
dotenv.config();
connectDB();
app.use(cors());
app.use(express.json());
app.use("/api", router)
// app.get('/', () => <h1>connect to backend < /h1>);
app.listen(PORT, () => {
console.log(`[server]: Server is running at https://localhost:${PORT}`);
});
PermalinkEnviroment setup
.env file look like this which has port for the backend and mangdb local host url
//env
PORT=4000
MONGO_URI=mongodb://localhost:27017/visualizationDB
PermalinkModal setup
model is a process of creating a predefined structure of how data has to be present in the database.
place it in models/dashboard.ts file of the server/ root directory of backend
// models/dashboard.ts
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const dashboardSchema = new Schema({
end_year: {
type: String,
required: false,
},
intensity: {
type: Number,
required: true
},
sector: {
type: String,
required: true,
},
topic: {
type: String,
required: true,
},
insight: {
type: String,
required: true,
},
url: {
type: String,
required: true,
},
region: {
type: String,
required: true,
},
start_year: {
type: String,
required: false,
},
impact: {
type: String,
required: false,
},
added: {
type: String,
required: true,
},
published: {
type: String,
required: true,
},
country: {
type: String,
required: true,
},
relevance: {
type: Number,
required: true,
},
pestle: {
type: String,
required: true,
},
source: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
likelihood: {
type: Number,
required: true
}
}, {
timestamps: true
});
// model of the schema
const dashboard = mongoose.model("dashboard", dashboardSchema);
// export the model
export default dashboard;
PermalinkRoute Setup
This a system in which you will specify the http methods to be used with how data to be fetched, modified, access using GET , POST, PUT, DEL methods of http .
place the file in routes/dashboardRoutes.ts
import express from "express";
import dashboard from "../models/dashboard";
const router = express.Router();
router.get("/getData", async (req, res) => {
const data = await dashboard.find({});
res.json(data);
})
router.get("/upload", (req, res) => {
try {
res.send("<h1>Connect to local host</h1>");
return res.status(200).json({ message: "connect to db" });
} catch (error) {
res.status(500);
}
});
router.post("/users", (req, res) => {
const body = req.body;
if (!body ||
!body.intensity) {
return res.status(400).json({ msg: "All fields are req..." })
;
}
})
export default router;
I hope you have find some information how to connect to mongoose localhost db in express server.