Robert Hovhannisyan
Robert Hovhannisyan

Reputation: 3341

Object's array property from Mongo is undefined

I'm successfully getting a document from my Mongo DB, but everything in that document is showing undefined. Here's an example:

...
  const user = await UserModel.findById(user_id).exec(); //Getting user normally

  console.log(user); // Shows the object normally with the "push_subscriptions" property
  console.log(user.push_subscriptions); // Shows undefined
  console.log(user.email); //Shows the email normally
...

Here's the screenshot of console:

enter image description here

Here is the "push_subscriptions" part of User's schema:

...
  push_subscriptions: {
    type: Array,
  },
...

Upvotes: 1

Views: 815

Answers (2)

Amir BenAmara
Amir BenAmara

Reputation: 686

you can use .lean() method to convert user to plain object :

const user = await UserModel.findById(user_id).exec().lean();

Upvotes: 2

JustRaman
JustRaman

Reputation: 1161

log user.toJSON() and see is there any push_subscription key is present. try user.toJSON().push_subscriptions as user is a mongoose Document you can try toJSON or toObject

As already discussed in Mongoose creating empty arrays?

Upvotes: 3

Related Questions