我从mongoose得到一个结果后,我正在尝试添加更多的东西,所以我添加一个_ext字段,它是我从查询中得到的扩展副本:
[...]
var schema = new mongoose.Schema(
{
_id: Number,
member_of: {type: [Number], required: true }
});
var User = mongoose.model('users', schema);
User.findById(1, function(err, result){
console.log(result);
输出:
{_ id:1,member_of:[1],__ v:0}
var user = result.toObject();
delete user.__v;
user._ext = {};
user._ext._id = user._id;
user._ext.name = '';
user._ext.displayName = '';
user._ext.imageUrl = '';
user._ext.member_of = [];
for (var i in user.member_of) {
var temp = {};
temp._id = user.member_of[i];
temp.name = '';
temp.displayName = '';
temp.imageUrl = '';
user._ext.member_of.push(temp);
}
console.log(user);
输出:
实际值:
{_id:1, member_of:[1], _ext: {_id:1, 名称: '', 显示名称: '', imageUrl:'', member_of:[[Object]] } }
预期:
{_id:1, member_of:[1], _ext: {_id:1, 名称: '', 显示名称: '', imageUrl:'', member_of:[{_ id:1,name:'',displayName:'',imageUrl:''}] } }
[...]
});
在_ext结构中查看member_of数组:我得到了[Object]
而不是{_id: 1, name: '', displayName: '', imageUrl: ''}
。我究竟做错了什么?
谢谢!
答案 0 :(得分:2)
实际上,你没有做错任何事,但是console.log()
只能在一定深度内进入嵌套对象:
> console.log([[[ "test" ]]])
[ [ [ 'test' ] ] ]
// add one more level, and...
> console.log([[[[ "test" ]]]])
[ [ [ [Object] ] ] ]
尝试将对象转换为(漂亮打印)JSON:
console.log(JSON.stringify(user, null, 2));
或者,或者,使用格式化字符串(输出不会那么漂亮):
console.log('%j', user);
或者使用具有指定深度的util.inspect
(其中null
表示infinite
):
var inspect = require('util').inspect;
console.log(inspect(a, { depth : null }))