首页 > 解决方案 > 使用其他字段填充文档

问题描述

我得到以下文件:

{
  "_id": "5b5df332879b4769739e3ed0",
  "name": "Back workout",
  "exercises": [{
    "_id": "5b5df9a7879b4769739e3ed1",
    "results": [{"reps":"10","weight":"85"}, {"reps":"8","weight":"70"}]
  }]
}

我想根据数据填充练习_id并附加results数据。

预期输出:

{
  "_id": "5b5df332879b4769739e3ed0",
  "name": "Back workout",
  "exercises": [{
    "_id": "5b5df9a7879b4769739e3ed1",
    "name": "EXERCISE_NAME",
    "results": [{"reps":"10","weight":"85"}, {"reps":"8","weight":"70"}]
  }]
}

我的架构如下所示:

const WorkoutSchema = new Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  exercises: [{
    _id: { type: Schema.Types.ObjectId, ref: 'Exercise' },
    results: Array,
  }],
  createdAt: Date,
  updatedAt: Date,
});

我的查询如下所示:

exports.listAll = async (request, h) => {
  const workoutCollection = await Workout
    .find()
    .populate('exercise');

  return { data: workoutCollection };
};

标签: node.jsmongodbmongoosemongoose-schemamongoose-populate

解决方案


推荐阅读