Mongoose 嵌套文档内部值的findOneAndUpdate

Mongoose 嵌套文档内部值的findOneAndUpdate,mongoose,Mongoose,我有以下MongoDB模式: const TaskSchema = new Schema ({ example: String, example1: String, example2: Date, example3: String, example4: [ { example5: Date, example6: String } ], subTasks: [

我有以下MongoDB模式:

const TaskSchema = new Schema ({
    example: String,
    example1: String,
    example2: Date,
    example3: String,
    example4: [
        {
            example5: Date,
            example6: String
        }
    ],
    subTasks: [
        {
            task: String,
            completed: Boolean
        }
    ],
    example7: String,
    example8: Date,
    example9: Date
})
我当前正在尝试访问子任务数组。它包含一个对象数组

通过以下查询,我可以根据使用查询参数传递的ID成功找到相应的文档:

const taskId = req.query.taskId
const query = { "subTasks._id": taskId}

const found = await task.findOne(query)
如果找到I console.log,它将在控制台中打印正确的任务

然而,当我使用这个逻辑调用findOneAndUpdate时,使用相同的参数,我得到一个404错误,表明它找不到正确的任务

const taskId = req.query.taskId
const query = { "subTasks._id": taskId}



await task.findOneAndUpdate(query, { "subTasks.completed": req.body.completed }, function(err, result) {
    if (!result) {
        res.status(404).send("Unable to find the task")
    } else {
        console.log("Successfully found the task!")
        console.log(result)
        console.log
    }
})
本质上,我想做的是:

  • 传递一个任务ID,该ID可用于查询我的数据库并找到正确的条目
  • 更新特定任务的completed属性
我不能完全理解我需要如何处理这个问题——感觉我需要做两个查询,一个是查找整个文档,另一个是查找对象子任务数组中的特定任务

有谁能帮我解决这个问题吗

如果这些都不清楚,请告诉我