2

I'm facing weird problem, when accessing values of object.

I'm using mongoose for querying MongoDB, (findOne operation in this specific).

Returned value is saved into product variable.

This code snippet

console.log(product);
console.log(product.auth); 

output this

{ _id: '56bde5cab581548421b5c1bf',
  product_identifier: 'oo',
  auth: { public: 'publickey', private: 'private_key' },
  created_at: 1455285691,
  deleted_at: null,
  flags: [],
  final_states: [ 3, 4 ] }
undefined

So my problem is that I'm not able to access inside values of an object. Just to make sure that it's not because of async behaviour of NodeJS, I reversed the order of both console.log statements, and it is still undefined After quick googling I find out that console.log is not reliable. So I did console.log(JSON.stringify(product)); which outputs

{"_id":"56bde5cab581548421b5c1bf","product_identifier":"oo","auth":{"public":"publickey","private":"private_key"},"created_at":1455285691,"deleted_at":null,"flags":[],"final_states":[3,4]}

(As expected) So for sure value is there. So I tried this

console.log(JSON.parse(JSON.stringify(product)).auth);

And boom!, it worked. (output - { public: 'publickey', private: 'private_key' })

I'm absolutely sure that it is not Object inside Array issue, which was most questions on the internet, I could find. What am I missing here?

PS - TBH, I'm really counting on mongoose bug

Edit - console.log(typeof product) outputs object, if that helps

Edit 2 - console.log(product.final_states) is working fine.

1 Answer 1

4

The type of document stored in MongoDB is BSON, we can try to convert the product to Object through toObject or toJSON

console.log(product.toJSON().auth);
Sign up to request clarification or add additional context in comments.

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.