Rename Mongoose return value padding

I am trying to return returned properties, as in Mysql AS . But with the renamed properties of the object.

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 Result

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

So how can I get the desired result?

+6
source share
3 answers

You can use aggregation and control the output field as follows

db.colleaction.aggregate ([{{Project: {_ ID: 0, home: "$ home_id", away: "$ away_id"}}])

+1
source

My solution is to use the conversion 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 filling:

Enter

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

Output

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

With filling:

Enter

 { "_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" } } 
0
source

Try lodash _.mapKeys, for example:

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

Source: https://habr.com/ru/post/1232247/


All Articles