繁体   English   中英

填充猫鼬查询时展平多个字段

[英]flatten multiple fields when populating a mongoose query

我在带有 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

}
});

当我用用户填充 dataPoint 时,我将玩家的团队和 _id 作为一个对象,我想将其展平为以下结构:Population 命令:

    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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM