简体   繁体   中英

Rename populate returned values Mongoose

I am trying to return returned properties, much like in Mysql 's AS . But with renamed object properties.

Query

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

Output

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

Desired Output

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

So how can I get the desired outcome?

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

db.collection.aggregate([{ $project:{_id:0, home:"$home_id", away:"$away_id"} }])

My solution is to use the transform function.

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;
        }
    }
});

Without populate:

Input

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

Output

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

With populate:

Input

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

Output

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

Try lodash's _.mapKeys, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM