【发布时间】:2020-11-29 07:36:12
【问题描述】:
所以我今天开始学习 mongoDB 和 moongoose。我有以下架构:
{
username: {
type : String,
required : true,
unique: true,
trim : true
},
routines : {
type: [
{
_id : mongoose.Schema.Types.ObjectId,
name : String,
todos : [
{
_id : mongoose.Schema.Types.ObjectId,
todo : String,
isCompleted : Boolean
}
]
}
],
}
}
例如:
{
"username": "John",
"routines": [
{
"_id" : 1234, //just for an example assume it to be as 1234
"name" : "Trip plan",
"todos" : [
{
"_id": 1213123,
"todo": "book flight",
"isCompleted" : "false"
}....
]
}......
]
}
我想要做的是,首先我会使用用户名从集合中选择一个文档,然后在例程(对象数组)中,我想通过 id 选择一个特定的例程,这将由用户在请求中给出正文,现在在选定的例程中,我想推入 todos 数组。
对于上面的例子,假设,选择用户名为 john 的文档,然后从例程数组中选择一个 _id 为 1234 的对象,然后在其 todos 中添加一个 todo。
我花了将近一天的时间来寻找如何做到这一点,同时我学习了一些概念,如 arrayFilters、投影。但是还是不知道怎么办。我也在 Stack Overflow 中阅读了很多答案,但我无法从中掌握很多。
PS:我对 MongoDB 和 mongoose 很陌生,我的问题可能很愚蠢,按照堆栈溢出标准可能不太好,对此我深表歉意。
【问题讨论】:
-
@Gibbs 我无法构造查询,我的意思是我应该使用 findoneandupdate,然后我给出了第一个过滤器,以便我可以选择正确的文档,但是我也应该找到的问题带有例程 id 的例程,在 findoneandupdate 哪里写?