将项目添加到来自Mongoose查询的BSON文档中的数组时出现意外的行为

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,name:'',displayName:'',imageUrl:'',member_of:[[Object]]}}

预期:

{_id:1,member_of:[1],_ext:{_id:1,name:'',displayName:'',imageUrl:'',member_of:[{_id:1,name:'',displayName:'' ,imageUrl:''}]}}

  [...] }); 

在_ext结构中查看member_of数组:我得到[Object]而不是{_id: 1, name: '', displayName: '', imageUrl: ''} 。 我究竟做错了什么? 谢谢!

实际上,你没有做错什么,但是console.log()只能recursion嵌套到一定深度的对象:

 > console.log([[[ "test" ]]]) [ [ [ 'test' ] ] ] // add one more level, and... > console.log([[[[ "test" ]]]]) [ [ [ [Object] ] ] ] 

尝试转换您的对象(漂亮打印)JSON:

 console.log(JSON.stringify(user, null, 2)); 

或者,也可以使用格式化string(虽然输出结果不会很漂亮):

 console.log('%j', user); 

或者使用具有指定深度的util.inspect (其中null表示infinite ):

 var inspect = require('util').inspect; console.log(inspect(a, { depth : null }))