【问题标题】:flatten multiple fields when populating a mongoose query填充猫鼬查询时展平多个字段
【发布时间】:2021-12-10 03:58:14
【问题描述】:

我在带有 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 作为对象,我想将其展平为以下结构: 人口指挥:

    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"
}

知道怎么做吗?

【问题讨论】:

    标签: javascript mongoose populate


    【解决方案1】:

    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)

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2014-01-08
      • 1970-01-01
      • 2023-03-21
      • 2020-10-17
      • 2019-04-06
      • 1970-01-01
      • 2021-11-03
      • 2018-06-01
      相关资源
      最近更新 更多