Home > database >  retrieving data from database according to query conditions
retrieving data from database according to query conditions

Time:12-12

    "_id":{"$id":"61b5eb36029b48135465e766"},
"name":"push-ups","link":"https://google.com",
"image":"https://google.com",
"gender":["0","1","2"],
"goal":["lw","gw","sf"],
"age":60,
"excersietype":"chest",
"__v":0

this is how my data is stored in database and I want to fetch data according to 3 condition

I got 3 queries from front gender goal and age and according to that I have to retrieve data

 const gender = req.query.gender;
    const age = req.query.age;
    const goal = req.query.goal
    const level = req.query.level

    if (level==='fb'){
        const getdata = new Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});
        console.log(getdata)
    }

Is this a good way to find the data because I am getting error

 UnhandledPromiseRejectionWarning: MongooseError: `Model.find()` cannot run without a model as `this`. Make sure you are not calling `new Model.find()`

I am getting above error while fetching

CodePudding user response:

Remove new operator

const getData = Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});

CodePudding user response:

The error is explicit : Make sure you are not calling 'new Model.find()'. Use const getdata = Forbeg.find(...).

However, you will immediately run into the next problem, as Mongoose models return thenables (Promise-like). console.log(getdata) will log Promise<pending>. You need to resolve your database call, either by doing

Forbeg.find(...).then( getdata => console.log(getData));

or (much more better!):

const getdata = await Forbeg.find(...);
console.log(getdata)

Even better, add .lean() to get simple JSON data instead of an array of Mongoose objects (faster), and .exec() to get a true Promise instead of a thenable :

const getdata = await Forbeg.find(...).lean().exec();
console.log(getdata)
  • Related