填充猫鼬查询时展平多个字段
flatten multiple fields when populating a mongoose query
我使用 expressjs 在 mongoose 中有以下架构
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)
我使用 expressjs 在 mongoose 中有以下架构
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)