In Node.js, To find documents in a MongoDB collection using Mongoose. we can use the "find()" method provided by Mongoose models.
Mongoose `find()` method supports sorting documents using `sort()` method based on one or more fields, either in ascending or descending order.
Mongoose supports limiting the number of documents returned using the `limit()` method and skipping a specific number of documents using the `skip()` method.
First, define a Mongoose model that corresponds to the collection we want to query.
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;
We can now use the "find()" method provided by the "EmployeeModel" to fetch data from "Employee" collection.
The "find()" method returns a list of documents that we can chain with other methods for ex: exec(), limit(), sort() and more, to further customize the query.
const EmployeeModel = require("./employeeModel"); async function findAllEmployee(req, res) { return await EmployeeModel.find() .then((employees) => { console.log("All Employee retrieve successfully:", employees); res.end(JSON.stringify(employees)); }) .catch((err) => { console.error("Error while fetching Employees:", err); res.end(JSON.stringify(err)); }); } module.exports = { findAllEmployee };
This will asynchronously find all documents from the "Employee" collection.
We can then handle the result of the query in the promise's "then()" method.
If successful, the resolved promise will contain an array of documents matching the query criteria. If an error occurs, the rejected promise will contain the error.
We can use "find()" method provided by the "EmployeeModel" to fetch data of specific `employee` from "Employee" collection.
const EmployeeModel = require("./employeeModel"); async function findEmployee(req, res, query) { // Find users with a specific name // using query params we can fetch data from db return await EmployeeModel.findOne({ email: query?.email }) .then((emp) => { console.log('Employee found:', emp); res.end(JSON.stringify(emp)); }) .catch((err) => { console.error('Error finding emp:', err); res.end("no employee found") }); } module.exports = { findEmployee };
This will asynchronously find specific documents from the "Employee" collection.
We can then handle the result of the query in the promise's "then()" method.
The results will be an object of a document that matches the query criteria.
import the `findEmployee` and `findAllEmployee` functions from the `employeeController` file and place them inside `/find-employee` and `find-all-employee` conditions respectively.
let http = require("http"); const url = require("url"); const dbConnection = require("./db"); const { findEmployee, findAllEmployee } = require("./employeeController"); http .createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/html" }); // Parse the requested URL const parsedUrl = url.parse(req.url, true); const { pathname, query } = parsedUrl; if (pathname === "/find-employee") { findEmployee(req, res, query); } else if (pathname === "/find-all-employee") { findAllEmployee(req, res); } else { res.end("Server Listening..."); } }) .listen(3002, () => { console.log(`server listening on port 3002!`); dbConnection(); });
To find employee data from DB, we use `GET` req, if we try to hit GET Request `http://localhost:3002/[email protected]` from a web browser. it will return the document from the Collection if it exists.