1

在我从 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: ''}] } }

        [...]
        });

Look member_of array in _ext structure: I got [Object] instead of {_id: 1, name: '', displayName: '', imageUrl: ''}. What am I doing wrong? Thanks!

4

1 回答 1

2

Actually, you're doing nothing wrong, but console.log() only recurses into nested objects up to a certain depth:

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

Try converting your object to (pretty-printed) JSON:

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

Or, alternatively, use a formatting string (output won't be as pretty though):

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

Or use util.inspect with an specified depth (where null means infinite):

var inspect = require('util').inspect;
console.log(inspect(a, { depth : null }))
于 2013-05-13T16:26:16.937 回答