Shubham Sharma
Shubham Sharma

Reputation: 381

search parameter in mongodb

user.js

exports.getProducts = async (name, brand) => {
 let queryFilters = { name , brand }   // ====>>> if brand or name is = '' then it not search
 queryFilters = JSON.parse(JSON.stringify(queryFilters));
 let userRecords = await model.find( queryFilters).exec();
 return userRecords
};

name and brand are query parameters and I want if name or brand is blank or undefined it does not pass in query parameter like localhost:3001/product?name=dj&brand= in this case it only search for name=dj not brand as it searches for name=dj and brand='' same if brand is given and name is undefined or blank. I also want like in SQL for e.g. if the name is dj and if I search for d then it also search for dj.Any help will be appreciated

Upvotes: 1

Views: 59

Answers (1)

Hasip Timurtas
Hasip Timurtas

Reputation: 980

You can do something like:

let queryFilters = {};

if(name != ''){
    queryFilters.name = name
};

if(brand != ''){
    queryFilters.brand = brand
};

if name or brand has value it will assign otherwise it will not include this fields.

Upvotes: 1

Related Questions