Home > Mobile >  A property on an object has data assigned to it, but returns undefied when it tries to access that p
A property on an object has data assigned to it, but returns undefied when it tries to access that p

Time:12-27

[
  {
    _id: 610be2c,
    msg: { text: 'sdsdsdsdsd' },
    sender: '600333',
    receiver: 5fea6e,
  },
  {
    _id: 610be2d,
    msg: { text: 'sdsdsdsdsdsdsdsdsdsdsd' },
    sender: '6003123',
    receiver: 608ffae,
  }
] 


Message.find({}, function(err, users) {
        
 
        if (users) {
            users.forEach(function(user) {
                console.log(`${user.receiver}`, 'receiver');
        });
});

The result in console.log for user.receiver:

undefined receiver
undefined receiver

I tried for user._id, user.sender and everything is ok. For user.receiver it returns undefined, although when I get the above two objects from the database I can see two objects and for the receiver property the data is attached. I tried to use user.receiver.toString() but I get an error: Cannot read property 'toString' of undefined

CodePudding user response:

That is because the value of receiver is not a string instead it's something 608ffae which JS reads as a variable(that might not be the case) and since it's not defined or declared it returns undefined:

Update:



[
  {
    _id: 610be2c,
    msg: { text: 'sdsdsdsdsd' },
    sender: '600333',
    receiver: '5fea6e',
  },
  {
    _id: 610be2d,
    msg: { text: 'sdsdsdsdsdsdsdsdsdsdsd' },
    sender: '6003123',
    receiver: '608ffae',
  }
] 

CodePudding user response:

update to this:

[
  {
    _id: 610be2c,
    msg: { text: 'sdsdsdsdsd' },
    sender: '600333',
    receiver: '5fea6e',
  },
  {
    _id: 610be2d,
    msg: { text: 'sdsdsdsdsdsdsdsdsdsdsd' },
    sender: '6003123',
    receiver: '608ffae',
  }
]
  • Related