skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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);
          
           })
    

  2. 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);
     }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search