Search API with multiple filed in nodejs
This blog we have seen mongodb basic and how is it
work with installation and after installation, we have already seen
mongodb basic, CRUD operation, connect mongodb with nodejs, read, update,
delete, POST, GET API etc.
we should not face
any problem while making Database, collection(table) and using the data in nodejs even whenever we will make
API. Read data from mongodb in nodejs
- # What is Mongoose
-
# Install Mongoose
-
# Make Simple GET Route for API
-
# Search with single field
- # Search with multiple fields
- # Test API
Now in this blog we will use mongoose. There is an
npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work
in an asynchronous environment. They created mongoose by improving
mongodb, with the help of which you can create schemas and models of mongoose's
movements.
Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want
to add only 4 fields, for this we create schemas.
Here you can also define TYPE in schemas like price type is
numeric but if any user wants to use quotes (" " ' ') then we can stop the
user for this.
in sort we can apply validation in mongoose but we
can't in directly mongodb.
What is MongoDB
MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.
MongoDB installation - CLICK HERE
MongoDB Basic Command -
CLICK HERE
About MongoDB vs SQL - CLICK HERE
CRUD in MongoDB - CLICK HERE
Object Like -
{ "_id": { "$oid": "659ad46e0382148123c82841" }, "name": "moto G60", "brand": "motorola", "price": 16500, "category": "mobile" }
MongoDB is a type of database that helps store and manage large amounts
of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a
fixed structure for the data, allowing you to store information in a more
versatile format.
- MongoDB is a NoSQL database.
- The data stored in a collection
- Collection don't have row and columns
- Data is stored in the form of object.
Install Mongoose
For this you need to copy this (npm i mongoose) and paste it in project's
terminal.
Make Simple GET Route for API
Here, we simple import express.js, configuration of mongodb file and schema
file and express.json for converting into json format after getting output
after that we create a /search route with /:key as a parameter. Then,
Product is our schema file and find method for all the data
gaining from the mongodb.
const express = require('express'); require('./config') const Product = require('./product') const app = express(); app.use(express.json()); app.get('/search/:key', async (req, resp) => { console.log(req.params.key); let data = await Product.find() resp.send(data) //resp.send('Done') }) app.listen(8000)
Run with nodemon index.js and after that we hit the request from postman.
Then we will search single data from single search
app.get('/search/:key', async (req, resp) => { console.log(req.params.key); let data = await Product.find( { "$or": [ { "name": {$regex: req.params.key}} ] } ) resp.send(data) //resp.send('Done') })
This code represents a route handler for an Express.js application. It
defines an HTTP GET endpoint at the path '/search/:key'.
The endpoint is designed to handle requests with a dynamic
parameter ':key', which represents the search key or term.
Database Query Using Mongoose:
let data = await Product.find({ "$or": [{ "name": {$regex:
req.params.key}}] });
This line uses the Mongoose library to query the MongoDB database. It searches
for documents in the 'Product' collection where the 'name' field matches the
provided search key using a case-insensitive regular expression.
Here's, only we are searched single search but after that we will create multiple search that's mean user search with value according to their demand like user search price's value, category, name, brand whatever users want.
Search with multiple fields
let data = await Product.find( { "$or": [ { "name": {$regex: req.params.key}}, { "brand": {$regex: req.params.key}} ] } ) resp.send(data) })
const express = require('express'); require('./config') const Product = require('./product') const app = express(); app.use(express.json()); app.get('/search/:key', async (req, resp) => { console.log(req.params.key); let data = await Product.find( { "$or": [ { "name": {$regex: req.params.key}}, { "brand": {$regex: req.params.key}} ] } ) resp.send(data) //resp.send('Done') }) app.listen(8000)
Disclaimer
All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.