To insert a document or row into a MongoDB collection using Mongoose and Node.js.
Define a schema that describes the structure of documents in your collection. we can define schemas using the "mongoose.Schema()" method.
Let's say you want to insert a document into an "employee" collection with fields for name, email, department and age.
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;
Create a new instance of the "Employee" model with the data required by `Employee schema`.
const EmployeeModel = require("./employeeModel"); async function addEmployee(req, res) { // payload we get from req.body; const name = req?.body?.name; const department = req?.body?.department; const email = req?.body?.email; const age = req?.body?.age; const newEmployee = new EmployeeModel({ name: "Alice Collin", department: "HR", email: "Alice.collin@example.com", age: 23, }); } module.exports = { addEmployee };
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; const name = req?.body?.name; const department = req?.body?.department; const email = req?.body?.email; const age = req?.body?.age; const newEmployee = new EmployeeModel({ name: "Alice Collin", department: "HR", email: "Alice.collin@example.com", 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 };
When we `save a document` using the `save()` method of the model, Mongoose automatically creates the corresponding `Collection` in the database and `Insert New Document` in the Collection.
This will asynchronously save the document to the MongoDB database.
If successful, the resolved promise will contain the saved document.
If an error occurs, the rejected promise will contain the error.
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 often use `POST` req, but in the above code we haven't applied the condition to check the `req.method`, 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.