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?
CodePudding user response:
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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>