Home > database >  How to access a Javascript object property whose type is undefined?
How to access a Javascript object property whose type is undefined?

Time:06-18

Given I have a JS object which gets is value from a mongodb database via this function

 const followed = await User.find(
      { _id: followie },
      {
        _id:0,"present": {
          $in: [followerid, "$followers"],
        }
      }
    );

When I console.log(followed), I get the following output

  console.log(followed[0]);
/*output : 
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
listening on port 8800 at time: 1655365344312
Mongodb Connected
{ present: true } ---------->  console.log output */

but when I try to access the "present" object within the followed dictionary, I get the type undefined that is:

 console.log(followed[0][0]);
/*output : 
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
listening on port 8800 at time: 1655365532137
Mongodb Connected
undefined   -------->  this is the console.log() */

Upon using typeof(followed[0]) I get the type as an object but when I try to get the typeof[0][0] it gives me the type as undefined. Where am I going wrong ? I have also tried followed[0].present and followed[0][present] with same results

CodePudding user response:

are you using mongodb or mongoose did you try followed[0]["present"]

CodePudding user response:

The problem with my approach and directly handling the .present key in the dictionary was that the mongoose data being sent was not in JSON format. The find() function returned an instance of the Mongoose Document class. The data was being returned in the ._doc key in the array within the followed object.

The solution to this was to use .lean() with the find object.

const followed = await User.find(
      { _id: followie },
      {
        _id: 0,
        present: {
          $in: [followerid, "$followers"],
        },
      }
    ).lean();

This results in a json object being returned which I am able to access with normal object.key or in this case followed[0].present or followed[0][0] code.

More details can be found here:https://mongoosejs.com/docs/populate.html

  • Related