【问题标题】:Finding a nested document and pushing a document into a nested document查找嵌套文档并将文档推送到嵌套文档中
【发布时间】: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 哪里写?

标签: mongodb mongoose


【解决方案1】:

你是在正确的轨道上,你确实想使用arrayFilter 来实现这一点。

这是一个简单的例子:

// the user you want.
let user = user;

await db.routines.updateOne(
    {
        username: user.username
    },
    {
        $addToSet: {
            "routines.$[elem].todos": newTodo
        }
    },
    {arrayFilters: [{'elem._id': "1234"}]}
);

【讨论】:

  • 我可以清楚地理解你的答案,但由于某种原因它不起作用。
  • 您能详细说明一下吗?更新失败了吗?您确定存在匹配的文档吗?
  • 是的,我确定存在匹配的文档,它没有给我任何错误,但它返回 { "ok": 0, "n": 0, "nModified": 0 }
  • 这是我的错,因为我写了一个语法错误。它应该是$[elem] 而不是[$elem]。我只是在本地运行它以确认。
猜你喜欢
  • 2018-03-09
  • 2016-07-01
  • 2018-09-19
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2021-02-25
  • 2016-08-16
相关资源
最近更新 更多