Home > Back-end >  Javascript Access an an Object in an Array
Javascript Access an an Object in an Array

Time:08-19

I'm fetching data from MongoDB, and the response is coming through fine, however it appears to be wrapped in array when it comes out of the User.find() function.

For example, one response is:

[{"_id":"62fe3c888e2776ef3c1a010f","username":"Drago D Trial","password":"U2FsdGVkX1867hs26KL0KitTGhWnP9tdVX6AcmI5pWE=","fullname":"Drago DaTrial","firstname":"","surname":"","email":"[email protected]","position":"QA Tester","userImage":"","locationCity":"","country":"","role":"","company":"","emailAuthorised":true,"professionalBio":"","positionRecentTitle":"","positionRecentCompany":"","companyAuthorised":"","isAdmin":false,"createdAt":"2022-08-18T13:20:08.045Z","updatedAt":"2022-08-18T13:21:02.619Z","__v":0}]

I'm accessing this through an api like this:

router.get('/inviteToJoinTeam/:token/:email', async (req, res) => {
    try {
      //verify the token against DB
      const userToken = (req.params.token)
      const indivEmailAdd = (req.params.email)

      // creating user auth
      try{
        const userDetails = await User.find({email: indivEmailAdd})
        const indivIDAdd = await userDetails (!want to access the data here and just get ID)

        res.send(indivIDAdd)


      }catch{
        console.log('failure')
      }

 
    } catch (e) {
      res.send('This isnt working');
    }
  
  });

How would you access this and just get the _id field out?

CodePudding user response:

If there is only one item in the array then - simply get the id property of the first item intthe returned array

const indivIDAdd = await userDetails[0]['_id'];

or using dot notation

 const indivIDAdd = await userDetails[0]._id;

if there are multiple results then map over the results and get the id from each

const ids = await userDetails.map(user => user._id);

CodePudding user response:

just use response[0]._id

Ps: Response is the array coming from the database

CodePudding user response:

According to me you have 2 solutions :

Option 1 use findOne instead of find :

const userDetails = await User.findOne({email: indivEmailAdd});

Option 2 access array / object with basic js:

const usersDetails = await User.find({email: indivEmailAdd});
const userDetails = usersDetails.at(0)._id; // or
const userDetails = usersDetails[0]['_id'];

CodePudding user response:

Try projection for the same it should work

const userDetails = await User.find({ email: indivEmailAdd }, { _id : 1 }) 

it will return array of ObjectId. if you need to get only one object then use findOne instead of find.

  • Related