bazz-dee
bazz-dee

Reputation: 697

nodejs "undefined" when stringifying Mongoose object

in my code i have following console logs:

console.log(JSON.stringify(department.locationFilter, null, 2));
console.log(JSON.stringify(department.locationFilter.geoLocation, null, 2));

The first log results in:

{
  "city": "Stuttgart",
  "radius": 50,
  "geoLocation": {
    "type": "Point",
    "coordinates": [
      9.1800132,
      48.7784485
    ]
  }
}

The second log results in:

undefined

When i log "geoLocation" in department.locationFilter it also results in false.

I don't understand why the geoLocation is undefined because it exists inside the JSON object.

For some more information, the department is read from mongodb.

Upvotes: 2

Views: 67

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26360

Mongoose is famous for generating weird and immutable objects. What you log is not necessarily JSON as you think but some of Mongoose's weirdos. Try to convert the Mongoose object to regular, plain object first : department = department.toObject().

Also, if you need only the data and not a full Mongoose object, you can query using .lean() :

Model.find({}).lean()

You'll get simple objects out of the box, and lean() is faster.

Upvotes: 2

Related Questions