Home > database >  How to query by passing dynamic key value pair in find() method of mongoose
How to query by passing dynamic key value pair in find() method of mongoose

Time:10-20

I want to send dynamic query to the mongoose find() method. For each iteration I need to send dynamic key and value in find method. Can someone help in this and I have tried below. The query for each iteration needs to be find({ idle_screen : value}), find({verify_address : value})

const relatedDoc: any = {
          idle_screen:1, 
          verify_address: 2, 
          update_address :3
       };
       Object.entries(relatedDoc).forEach(async ([key, value]) => {  
        // Here i want to add key as property in object
        const query = { key : value} // actual o/p = {key : 1} , expected o/p = {idle_screen : 1} , {verify_address : 2} 
        var appointmentRefDocs = await appointment.find(query);
      
       })```

 Thanks in advance.

CodePudding user response:

use for of loop for async operation .

const relatedDoc: any = {
      idle_screen:data.idle_screen, 
      verify_address: data.verify_address, 
      update_address :data.update_address
   };


 for (const [key, value] of Object.entries(relatedDoc)) {
  const query = {[key] : value}
  var appointmentRefDocs = await appointment.find(query);
 }

CodePudding user response:

Here is the updated answer :

const relatedDoc: any = {
          idle_screen:1, 
          verify_address: 2, 
          update_address :3
       };
       Object.entries(relatedDoc).forEach(async ([key, value]) => {  
        
        const query = { [key] : value};
        var appointmentRefDocs = await appointment.find(query);
      
       })

CodePudding user response:

const dynamicFindQuery = async (data: any) => {
        const relatedDoc: any = {
            idle_screen: data.idle_screen,
            verify_address: data.verify_address,
            update_address: data.update_address
        };
    
        for (const [key, value] of Object.entries(relatedDoc)) {
            const query = { [key]: value }
            const appointmentRefDocs = await appointment.find(query);
        }
    }

If you use Typescript, then you can use Record<string, any> instead of any as the function parameter's type.

  • Related