简体   繁体   中英

flatten multiple fields when populating a mongoose query

I have the following Schema in mongoose with expressjs

const userSchema = new mongoose.Schema({
    name: {
        type: String, 
        required: true
    }, 
    team: {
        type: String
    }, 
});


const dataPointSchema = new mongoose.Schema({
type: {
    type: String, 
    required: true,
    min: 2
}, 
value: {
    type: String, 
    required:  true
},
recorder: {
    type: String,
    required: true
},
player: 
  {type: Schema.Types.ObjectId, ref: 'User'},
date: {
    type: Date,
    default: Date.now

}
});

When I populate the dataPoint with the User, I get the player's team and _id as an object, and i want to flatten it to the below structure: Population command:

    Datapoint.find({}).populate([{path:'player',select:['team']}])

current output:

{
  player: {_id:"_id from User",team:"team from User"},
  _id: '1',
  type: 'shot',
  value: 'made',
  recorder: 'David',
  date: ' 2021-09-21T21:12:00.025Z',
  __v: 0,
}

Desired outout

{
  player: "_id from User",
  _id: '1',
  type: 'shot',
  value: 'made',
  recorder: 'David',
  date: ' 2021-09-21T21:12:00.025Z',
  __v: 0,
  player.team: "team from User"
}

Any idea how to do this?

 const player = { player: {_id:"_id from User",team:"team from User"}, _id: '1', type: 'shot', value: 'made', recorder: 'David', date: ' 2021-09-21T21:12:00.025Z', __v: 0, } const flatPlayer = {...player ,player: player .player._id,team: player .player.team} console.log(flatPlayer)

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