Home > other >  The array doesn't behave like an array
The array doesn't behave like an array

Time:02-27

I'm working with express, node and mongoose. If I access my mongoDB database and console.log it, I get my array:

module.exports ={
  stories: function(req, res, next){
    
      Story.find(function(err, stories){
      


  if(err) return handleError(err);

  console.log(stories)

  res.render('dashboard', {
  err,
  stories
  })
  })
  }
}

The output

 '0': {
        _id: new ObjectId("6206613aeb4f95fd983f94ba"),
        username: 'David N.',
        content: '   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,   content,v',
        date: 2022-02-11T13:14:34.461Z,
        __v: 0
      }

BUT I cannot perform dot notation!

module.exports ={
  stories: function(req, res, next){

      Story.find(function(err, stories){



  if(err) return handleError(err);

  console.log(stories.username)

  res.render('dashboard', {
  err,
  stories
  })
  })
  }
}

Then the output is: undefined

Can please someone explain to me, what is going on and how I can just access the username for example?

CodePudding user response:

Since stories is an array, you can access the elements inside the array using indexing. In this case if you want to log the username of 1st story, you need to do

console.log(stories[0].username) 

CodePudding user response:

Look like Stories is an array so you need to do stories[0].username

  • Related