Mongoose,子文档是对象而不是json

时间:2012-10-14 20:27:30

标签: javascript mongodb mongoose

我使用mongoose查询我的mongodb,但我不明白为什么返回的子文档只是Object类型,而不是JSON。

使用

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

返回

[ { _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] } ] } ]

像anim,size,projectile,upgrade这样的子文档是Object,我需要嵌套信息,如何获取信息?不进行其他查询?

3 个答案:

答案 0 :(得分:1)

所有docs和subdoc都是JavaScript中的对象。只是console.log在调用util.inspect格式化文档以进行输出时使用默认深度2。您可以自己调用util.inspect来输出文档的所有级别:

var util = require('util');

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

答案 1 :(得分:0)

使用find()进行Mongoose查询将返回Mongoose Documents(而不是JSON)。您可以使用lean()方法返回POJO:

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

但JohnnyHK对控制台日志的说法是正确的,它只会将嵌套文档显示为[Object]。

更新:请注意使用.lean()将返回对象,您可能会忽略任何虚拟字段或特殊的getter。

答案 2 :(得分:0)

JohnnyHK是正确的,但如果你只是想注销JSON就是一个更简单的方法

console.log(tower.toJSON());

你可以看到我对Rodrigo的评论,说明为什么会有效。