[英]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. 我正在使用猫鼬查询mongodb,但我不明白为什么返回的子文档只是Object类型,而不是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?
无需再次查询?
The all docs and subdocs are objects in JavaScript. 所有文档和子文档都是JavaScript中的对象。 It's just that
console.log
uses the default depth of 2 when calling util.inspect
to format your document for output. 只是在调用
util.inspect
格式化文档以进行输出时, console.log
使用默认深度2。 You can output all levels of the document by calling util.inspect
yourself: 您可以自己调用
util.inspect
来输出文档的所有级别:
var util = require('util');
hero.find({} ,{'deck' : {$elemMatch:{name:'Guard Tower'}}}, function(err, tower) {
console.log(util.inspect(tower, false, null));
});
Making the query on Mongoose using find() as you did will return Mongoose Documents (not JSON). 使用find()在Mongoose上进行查询,将返回Mongoose文档(不是JSON)。 You can use the lean() method to return POJOs:
您可以使用lean()方法返回POJO:
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]. 但是,JohnnyHK所说的关于控制台日志的说法是正确的,它只会将嵌套的文档显示为[Object]。
UPDATE: Beware that using .lean() will return objects and any virtual fields or special getters you might have will be ignored. 更新:请注意,使用.lean()将返回对象,并且您可能拥有的任何虚拟字段或特殊吸气剂将被忽略。
JohnnyHK is correct however a simpler approach if you just want to log out JSON would be JohnnyHK是正确的,但是如果您只想注销JSON,则更简单的方法是
console.log(tower.toJSON());
You can see my comment to Rodrigo about why this works. 您可以查看我对Rodrigo的评论,以了解其工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.