Search code examples
node.jsmongodbmongoosenodes

Pass multiple queries in GET request to mongodb


// route.js

const express = require('express');

const router = express.Router();

const userHandler = require('../handler/user');

router.get('',userHandler.getUser);

module.exports = route

-

// Handler.js

const userController = require('../../core/controller/user');

// get user

getUser = async (req, res, next) => {
    //console.log(req)
    try {
        let user = await userController.getUser(req.params.id, req.query.employeeStatus, req.query.department)
        req.data = user
        next()
    }
    catch (e) {
        req.status = 400;
        next(e)
    }
}

module.exports = {getUser}

-

// controller.js

exports.getUser = async (userId,employeeStatus,department) => {

    let userRecords = await userModel.getUser(userId,employeeStatus,department);
    userRecords = userRecords.map(it => {
        return {
            id: it._id,
            firstName: it.firstName,
            lastName: it.lastName,
            pic: it.pic,
            gender: it.gender,
            dob: it.dob,
            maritalStatus: it.maritalStatus,
            nationality: it.nationality,
            streetAddress: it.streetAddress,
            city: it.city,
            state: it.state,
            postalCode: it.postalCode,
            country: it.country,
            phone: it.phone,
            email: it.email,
            jobTitle: it.jobTitle,
            department: it.department,
            dateOfJoining: it.dateOfJoining,
            employeeStatus: it.employeeStatus,
            kra: it.kra,
            assignedSupervisor: it.assignedSupervisor,
            assignedSubordinate: it.assignedSubordinate,
            workExperience: it.workExperience,
            skills: it.skills,
            password: it.password
        }
    })
    return userRecords;
}

-

// query.js

exports.getUser = async(userId, employeeStatus, department) => {

    var whereClause = '';
    if (department) {
       var whereClause ={ "department":department}
       console.log(whereClause)
       console.log( Object.keys(whereClause).length)
    } 
    if(userId) return await model.find({"_id":userId}).exec();
    if (employeeStatus){
        console.log('debewbfewhfui')
        if ( Object.keys(whereClause).length) {
            console.log(whereClause)
            whereClause +=  ','
            console.log( whereClause.toSource())
            console.log(whereClause.hasOwnProperty("employeeStatus"))

            whereClause += {"employeeStatus":employeeStatus}
        }
        console.log(whereClause)
        //whereClause = {"employeeStatus":employeeStatus}
        console.log('e',  Object.keys(whereClause).length)
    // }])
        // console.log(department)
        // return await model.find({  $and: [ { $or: [{"employeeStatus": employeeStatus }] },{"department": department} ]  }).exec();
        // return await model.find({"employeeStatus":employeeStatus}).find({"department":department}).exec();
    }
    // if(department) {
    //     console.log('55')
    //     return await model.find({"department":department}).exec();
    // };
    // if (Object.keys(whereClause).length) {
    //     console.log(whereClause)
    //     whereClause = whereClause + ','
    // }
    var query = await model.find({$and : [whereClause] }).exec();
    console.log('fssd',JSON.stringify(whereClause))
    return query
}

I want if we pass any data department or employeestatus in query it will return data as required and if we dont pass any query then it will search all users. Can anyone help me please?


Solution

  • To conditionally compose the query filters depending on the parameters passed into the function, this should work:

    query.js
    
    exports.getUser = async (userId, employeeStatus, department) => {
      let queryFilters = { userId, employeeStatus, department };
      // The JSON stringify and parsing below would help remove undefined filter values
      // i.e if userId is not provided, while employeeStatus and department are given 
      // the queryFilters object would only contain employeeStatus and department.
      queryFilters = JSON.parse(JSON.stringify(queryFilters))
      return model.find(queryFilters);
    }