【发布时间】:2021-05-29 06:13:55
【问题描述】:
假设我的 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
}
]
}
]
}
Workout 对象可以在练习数组中包含多个锻炼对象,并且每个锻炼对象可以在 sets 数组中包含多个集合对象。我正在尝试为某个集合实现删除功能。我需要检索存储我要删除的集合的锻炼。我可以访问用户的 ID(存储在上下文中)、锻炼 ID 和要删除的集合 ID 作为 .findOne() 的参数功能。但是,我不确定是否可以遍历锻炼对象中不同级别的数组和对象。这是我尝试过的:
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 对象。我想从这个函数的参数中省略executiveID,只使用setID,但我不确定如何遍历对象数组来访问它的值。这是可能的还是我应该以另一种方式去做?谢谢。
【问题讨论】:
标签: mongodb mongoose mongodb-query