In MongoDB, Collections are created implicitly when you first store data in them.
When using Mongoose, a popular MongoDB object modelling tool for Node.js, we typically define schemas and models that correspond to collections.
Mongoose handles creating collections for us based on these models.
Define a schema that describes the structure of documents in your `collection`. we can define schemas using the "mongoose.Schema()" method.
create a file name `employeeModel.js` and paste the below code.
const mongoose = require('mongoose'); const employeeSchema = new mongoose.Schema({ name: String, email: String, department: String, age: Number }); // Define a model based on the schema const Employee = mongoose.model('Employee', employeeSchema); module.exports = Employee;
Now, we can use the "Employee" model to store data in the MongoDB collection.
When we save a document using the model, Mongoose automatically creates the corresponding collection in the database if it doesn't exist:
create a file name `employeeController.js` and paste the below code.
const EmployeeModel = require("./employeeModel"); async function addEmployee(req, res) { // payload we get from req.body; // Creating Employee with mock data const newEmployee = new EmployeeModel({ name: "Alice Collin", department: "HR", email: "[email protected]", age: 23, }); await newEmployee .save() .then((emp) => { console.log("Employee saved successfully:", emp); res.end("Employee saved successfully"); }) .catch((err) => { console.error("Error saving employee info:", err); }); } module.exports = { addEmployee };
A new "employee" document is created using the "Employee" model and saved to the MongoDB database.
If the "employee" collection doesn't exist, Mongoose will create it automatically based on the schema defined earlier.
import the `addEmployee` function from the `employeeController` file and place it inside the `/add-employee` condition.
let http = require("http"); const dbConnection = require("./db"); const { addEmployee } = require("./employeeController"); http .createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/html" }); if (req?.url === "/add-employee") { addEmployee(req, res); } else { res.end("Server Listening..."); } }) .listen(3002, () => { console.log(`server listening on port 3002!`); dbConnection(); });
To Add data in DB we use `POST` req, but in the above code we haven't applied the condition to check the `req.method` condition, so even if we try to hit GET Request `http://localhost:3002/add-employee` from a web browser. it will save a new document in Collection with mock data which we have added in the `addEmployee` function.