0

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?

2
  • If you just need a single entry use the findOne method instead of find. Commented Aug 19, 2022 at 6:59
  • User.find() always returns an array. To get only the field(s) from the resulting documents, use projection in the query. Commented Aug 19, 2022 at 7:04

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

just use response[0]._id

Ps: Response is the array coming from the database

Comments

1

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.

Comments

0

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'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.