使用Mongose更新数组内的值时,通过recordId和userId查找记录



如果标题有点混乱,我很抱歉,但我不知道如何重新措辞。

所以我有以下对象:

{
"_id": "622dec2e037d7ae286b366c9",
"name": "Moriel Odeski",
"email": "moriel96@gmail.com",
"street": "Ben Gurion",
"city": "Be'er Sheva",
"zipcode": 329886,
"tasks": [
{
"id": "1",
"title": "Test",
"completed": true
},
{
"id": "2",
"title": "Test2",
"completed": false
},
{
"id": "3",
"title": "Test3",
"completed": false
},
{
"id": "4",
"title": "Do The Dishes",
"completed": false
}
],
"posts": [
{
"id": 1,
"title": "That's Moriel's Post",
"body": "According to my evaluations 0-0"
},
{
"id": 2,
"title": "Something about something",
"body": "That's interesting"
}
]
}

我正在尝试编写一个函数,该函数获得userIDtaskID,通过调用它,它将任务的.completed更改为true,其中id = taskIDuserId : userID

我有以下功能不起作用:

const markTaskCompleted = (userID , taskID) =>
{
return new Promise((resolve, reject) =>
{
User.findOneAndUpdate({id : userID , tasks : {$elemMatch: {id : taskID}}},
{$set: {"tasks.$.completed" : true}},
{"new" : true , "safe" : true , "upsert" : true} , function(err , data)
{
if(err){reject(err)}
else
{
resolve(data.tasks)
}
})
})
}

它抛出:

Plan executor error during findAndModify :: caused by :: The positional operator did not find the match needed from the query.

我哪里出了问题?

我觉得很难阅读您的代码,因为它看起来不干净。。所以也许首先最好把它弄得更干净。。我想?

const markTaskCompleted = async (userID , taskID) => await User.findOneAndUpdate({
id: userID, 
tasks: {$elemMatch: {id: taskID}}
},
{$set: {"tasks.$.completed": true}},
{"new": true , "safe": true , "upsert": true}, 
})

你在回调中使用了回调,所以我觉得它不干净。我用的是async/await。我希望这个在你看来也更干净。

官方的猫鼬文档也使用await作为findOneAndUpdate()方法。https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-启动

看看吧。你能检查一下我写的代码是否有效吗?

最新更新