猫鼬更新嵌套模式

时间:2019-05-06 16:53:41

标签: mongoose

我找不到在Mongoose中更新嵌套模式的有效解决方案。

模式:

const boardSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    tasks: { type: [taskSchema] }
  },
)

const taskSchema = new mongoose.Schema(
  {
    title: { type: String, required: true },
    priority: { type: Number, default: 0, required: true }
  },
)

const Board = mongoose.model('Board', boardSchema)
const Task = mongoose.model('BoardTask', taskSchema)

如何更新board.tasks数组中的任务?我已经尝试过

const taskId = 'demo'
const taskUpdate = {title: 'Demo', priority: 0}

Board.findOneAndUpdate({ taskId: taskId }, taskUpdate)

taskSchema.findByIdAndUpdate(taskId, taskUpdate)

Board.findById(boardId).then(board => {
    BoardTask.findOneAndUpdate(board.taskId, taskUpdate)
})

我想我这里必定有一点遗漏,甚至不确定我是否应该尝试从taskSchema或Task模型之外更新它。

1 个答案:

答案 0 :(得分:0)

如果要更新保存在Board模型中的任务,则不需要Task集合,因此不需要Task模型。更新查询将如下所示:-

const getUpdate = (update) => {
  const updateQuery = {};
  Object.keys(update).forEach(key => {
    updateQuery[`tasks.$.${key}`] = update[key];
  });
  return updateQuery;
}

const update = {
  title: "newtitle",
  taskId: "22"
}

Board.findOneAndUpdate(
  { _id: boardId, “tasks._id”: taskId },
  {$set: getUpdate(update) }
);

尽管如此,我还是建议您使用其他Task集合,并在任务中保存父级Board ID的引用。