对嵌套文档值使用MongoDB.findOne()函数 [英] Using MongoDB .findOne() function with nested document value
本文介绍了对嵌套文档值使用MongoDB.findOne()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的MongoDB集合中有这个文档,工作:
{
_id: ObjectId("60383b491e2a11272c845749") <--- Workout ID
user: ObjectId("5fc7d6b9bbd9473a24d3ab3e") <--- User ID
exercises: [
{
_id: ObjectId("...") <--- Exercise ID
exerciseName: "Bench Press",
sets: [
{
_id: ObjectId("...") <--- Set ID
},
{
_id: ObjectId("...") <--- Set ID
}
]
}
]
}
锻炼对象可以在练习数组中包含多个练习对象,每个练习对象可以在集合数组中包含多个集合对象。我正在尝试为某个集合实现删除功能。我需要检索我想要删除的集合所存储的锻炼。我可以访问要作为.findOne()函数的参数删除的用户ID(存储在上下文中)、练习ID和集合ID。但是,我不确定是否可以遍历锻炼对象中不同级别的数组和对象。这是我尝试过的:
const user = checkAuth(context) // Gets logged in user details (id, username)
const exerciseID, setID // Both of these are passed in already and are set to the appropriate values
const workoutLog = Workout.findOne({
user: user.id,
exercises: { _id: exerciseID }
});
这将返回一个空数组,但我期望的是包含我想要删除的集合的整个Workout对象。我想从这个函数的参数中省略ExerciseID,只使用setID,但我不确定如何遍历对象数组来访问它的值。这可能吗,或者我应该用另一种方式来做这件事?谢谢。
推荐答案
匹配数组时,如果指定查询如下:
{ exercises: { _id: exerciseID } }
MongoDB尝试执行exact match on the document。因此,在本例中,MongoDB将只匹配exercises
数组中的文档,该数组的格式与{ _id: ObjectId("...") }
完全相同。由于exercises
中的文档具有其他字段,因此即使_id
相同,这也永远不会产生匹配。
您要做的是query a field of the documents in the array。然后,完整的查询文档将如下所示:
{
user: user.id,
"exercises._id": exerciseID
}
这篇关于对嵌套文档值使用MongoDB.findOne()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文