Search code examples
node.jsmongodbexpressmongoosefind

Find user dynamically


** I want to create a function that accepts any data like id, email, etc., and finds the user based on the input passed to it. **

ex:

const user = async(input)=>{
    const result = data.findOne({input}); //whatever the input I passed I want the user
    return result;
}

should I Pass the key with input like (input, key)?? so I need one common function to find the user data dynamically


Solution

  • Assuming you know ahead of time what fields the data might be found in, use $or to check them all:

    data.findOne({$or: [
        {id: input},
        {email: input},
        {username: input}
    ]})