Home > Software design >  How to use data in array in javascript?
How to use data in array in javascript?

Time:09-27

I am using nodejs as backend and mongodb. So I query using the email and get a array of data and how to use that data.

User.find({email: ""}, (err,response) =>{
--
--
});

Here I get data

{
  email: "..",
  name: "..",
  friend: "..",
}

So can I use response.email to get email, and response.name to get name?

CodePudding user response:

If the response is array use response[index].name or if email is unique in that collection you can use User.findOne(), it will return single object as response, Where you can access object properties directly.

CodePudding user response:

There are 2 cases. Chose whatever suits your situation

  1. If email is unique

    // use findOne (it will return only single object)
    User.findOne({ email: "[email protected]" }, (err, response) => {
        if (err)
            throw new Error(err);
    
        if (response) // to check if something is returned or not
            console.log(response.name);  // you can get any value from response.yourRequiredField or console.log(response) for full object
        else
            console.log("Nothing in response");
    });
    
  2. If email is not unique

     // use find (this will return array of matching objects)
     User.find({ email: "[email protected]" }, (err, response) => {
         if (err)
             throw new Error(err);
    
         if (response.length > 0) // to check if something is returned or not
             console.log(response[0].name); // you need to use index here OR console.log(response) for full array OR console.log(response[0]) for full object at given index
         else
             console.log("No matching object in response");
     });
    
  • Related