我有下面的Schema在mongoose与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
}
});
当我用用户填充数据点时,我得到球员的团队和_id作为一个对象,我想把它扁平化到下面的结构:人口命令:
Datapoint.find({}).populate([{path:'player',select:['team']}])
当前输出:
{
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,
}
所需文稿
{
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"
}
你知道怎么做吗?
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)