MartinElvar
MartinElvar

Reputation: 5804

Mongoose, sub document is objects and not json

I am querying my mongodb using mongoose, but i don't understand why the returned sub docs are just of type Object, instead of JSON.

Using

  hero.find({} ,{'deck' : {$elemMatch:{name:'Guard Tower'}}}, function(err, tower) {
    console.log(tower);
  }

returns

[ { _id: 507ac406ba6ecb1316000001,
    deck: 
     [ { name: 'Guard Tower',
         description: 'This tower shoots stuff.',
         cost: 13,
         sellValue: 7,
         radius: 180,
         speed: 40,
         dmg_min: 0,
         dmg_max: 0,
         actual_height: 40,
         sprite: 'guardtower_red.png',
         anim: [Object],
         size: [Object],
         projectile: [Object],
         upgrade: [Object] } ] } ]

Subdocument like anim, size, projectile, upgrade, is Object, i need the information nested, how can i get the information? Without making another query?

Upvotes: 0

Views: 1387

Answers (3)

Rodrigo Reis
Rodrigo Reis

Reputation: 1941

Making the query on Mongoose using find() as you did will return Mongoose Documents (not JSON). You can use the lean() method to return POJOs:

hero
 .find({} ,{'deck' : {$elemMatch:{name:'Guard Tower'}}})
 .lean()
 .exec(function(err, tower) {
   //tower is a JSON here
   console.log(tower);
 });

But what JohnnyHK said it's true about the console log, it will only show nested documents as [Object].

UPDATE: Beware that using .lean() will return objects and any virtual fields or special getters you might have will be ignored.

Upvotes: 0

Jason Cust
Jason Cust

Reputation: 10899

JohnnyHK is correct however a simpler approach if you just want to log out JSON would be

console.log(tower.toJSON());

You can see my comment to Rodrigo about why this works.

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311865

The all docs and subdocs are objects in JavaScript. It's just that console.log uses the default depth of 2 when calling util.inspect to format your document for output. You can output all levels of the document by calling util.inspect yourself:

var util = require('util');

hero.find({} ,{'deck' : {$elemMatch:{name:'Guard Tower'}}}, function(err, tower) {
    console.log(util.inspect(tower, false, null)); 
});

Upvotes: 1

Related Questions