Ad

Mongoose Model.find(filteredQuery) Returns Empty Array

I have a Node.js back-end that communicates with my MongoDB, and I need to filter out some results from the database. The problem is, when I send the query, I just receive an empty array in return.

function setTOQuery() {
            let path;
            let filter;
            let query = {};
            return new Promise((resolve)=> {
                if(params.A.length === 0 ) {
                    path = "booked.services";
                    filter = { '$exists': true };
                    query[path] = filter;
                } else {
                    path = "booked.services.service_id";
                    filter = { '$in': params.A };
                    query[path] = filter;
                }
                resolve(query);
            });
        }

async function retrieveData() {


            const toQ = await setTOQuery();

            CustomerModel.find({
                toQ
            }, (err, docs) => {
                    if(err) console.log(err);
                    console.log(toQ);
                    console.log(docs);
                    res.status(200).send(docs);
                    return docs;
            })
        }

        retrieveData();

console.log(toQ) returns { 'booked.services': { '$exists': true } }

so I don't understand what's wrong here. With both queries I just receive []. I'm suspecting something with the async/await is wrong, but I don't know what exactly.

Any help would be appreciated

Ad

Answer

if console.log(toQ) returns { 'booked.services': { '$exists': true } }

then toQ is an object already and you should use it without keys like:

CustomerModel.find(
                toQ
            , (err, docs) => {
                    if(err) console.log(err);
                    console.log(toQ);
                    console.log(docs);
                    res.status(200).send(docs);
                    return docs;
            })

Ad
source: stackoverflow.com
Ad