MongoDb returns empty array when I pass object to filter results (but doesn't when I enter filter directly)

Viewed 67

I can find similar questions, but none seem to fix my issue.

When I construct an object from a req.body to use as a filter for searching my mongodb database, I get back an empty array. When I type in the object into the .find method, i get the results I want. I need to build the filter beforehand from the req.body so I can use this dynamically.

Can someone explain how to build a filter object to search mongodb with? Or tell me what is wrong with my code. The req.body comes from a form on my website, then node.js is used to transform the req.body into an object and pass it to mongo db.

Here is my nodejs route file:

const mongoFilter = {
    Name : null,
    Gender : null
}

router.post('/search', (req, res)=>{
    let filter = Object.create(mongoFilter);
    filter.Name = req.body.Name;
    filter.Gender = req.body.Gender;

    mongoControls.quickSearch(filter, function(err, results){
        if(err){
            console.log('an error has occurred')
            console.log(err);
            return;
        }else if(results){
            console.log('success');
            res.send(results)
        }else{
            console.log('no documents found')
        }
    });
})

my mongoControls.js file: (This doesnt work when the filter is passed to .find(), but below is what works

module.exports = {
    quickSearch: async function(filter, callback){
        try{
            await client.connect()
            const collection = client.db(process.env.DB_NAME).collection(process.env.COLL_NAME);
            people = [];
            await collection.find(filter)
                .forEach(doc =>{
                    people.push(doc)
                })
            callback(null, people);  
        }catch(err){
            console.log('An error has occurred')
            callback(err, null)
        }finally{
            console.log("Closing connection");
            await client.close();
        }   
    }
    
}

*If I replace the .find method with this below it works, but I need to build the filter from req.body and I don't understand why it doesnt work above

await collection.find({Name:"John"})
                .forEach(doc =>{
                    people.push(doc)
                })
1 Answers

Your code is fine. I've checked it and it worked for me.

check your form and check the input field's name.

 <form> 
<input name="Name" id="Name"  ...  />
<input name="Gender" id="Gender"  ...  />
</form>
Related