重命名填充返回的值Mongoose

时间:2015-09-25 07:44:57

标签: javascript node.js mongodb

我正在尝试返回返回的属性,就像在Mysql' s AS中一样。但是重命名的对象属性。

查询

Games.find({leagueID:leagueID, result:{$ne: null}}).populate('home_id away_id').sort({date: -1}).execAsync()

输出

{
    home_id: {
        ...some details
    },
    away_id: {
        ...some details
    }
}

所需输出

{
    home: {
        ...some details
    },
    away: {
        ...some details
    }
}

那么我怎样才能得到理想的结果呢?

3 个答案:

答案 0 :(得分:0)

您可以使用聚合并像这样操作输出字段

db.colleaction.aggregate([{$项目:{_ ID:0,家用: “$ HOME_ID”,远: “$ away_id”}}])

答案 1 :(得分:0)

我的解决方案是使用转换功能。

GamesSchema.set('toJSON', {
    transform: function(doc, ret, options) {   
        if (mongoose.Types.ObjectId.isValid(ret.home)) {
            ret.homeId = ret.home;
            delete ret.home;
        }
        if (mongoose.Types.ObjectId.isValid(ret.away)) {
            ret.awayId = ret.away;
            delete ret.away;
        }
    }
});

没有填充:

输入

{
    "_id": "sD95OhsGrWVIqmTLVeuQdkna",
    "leagueID": 1000,
    "home": "404d1d9f68c3bb386b50f440" // ObjectId
    "away": "504d1d9f68c3bb386b50f450" // ObjectId
}

输出

{
    "_id": "sD95OhsGrWVIqmTLVeuQdkna",
    "leagueID": 1000,
    "homeId": "404d1d9f68c3bb386b50f440"
    "awayId": "504d1d9f68c3bb386b50f450"
}

使用填充:

输入

{
    "_id": "sD95OhsGrWVIqmTLVeuQdkna",
    "leagueID": 1000,
    "home": "404d1d9f68c3bb386b50f440" // ObjectId
    "away": "504d1d9f68c3bb386b50f450" // ObjectId
}

输出

{
    "_id": "sD95OhsGrWVIqmTLVeuQdkna",
    "leagueID": 1000,
    "home": {
        "_id": "404d1d9f68c3bb386b50f440",
        "name": "Home"
    }
    "away": {
        "_id": "504d1d9f68c3bb386b50f450",
        "name": "Away"
    }
}

答案 2 :(得分:0)

尝试lodash的_.mapKeys,如下所示:

const newObject = _.mapKeys(oldObject.toJSON(), (value, key) => {
            if (key === 'oldKey') return 'newKey';
            return key;
          });