代码之家  ›  专栏  ›  技术社区  ›  p7adams

Mongoose/MongoDB:如何更新向下嵌套4级的项?

  •  0
  • p7adams  · 技术社区  · 7 年前

    在我的mongo数据库中,我有这样一棵树:

    -shopping-lists
      |- list
           |-products
               |-item
               |-item
     |- list
               |-products
                   |-item
                   |-item
    

    我需要找到我正在更新的购物清单,然后转到产品数组,在里面找到一个项目并更新一个属性。 我试图在几个小时内解决这个问题,但没有找到任何解决方案。 enter image description here

    2 回复  |  直到 7 年前
        1
  •  3
  •   p7adams    7 年前

    经过6个小时的调查,我找到了答案。 对于你们中的任何人来说,有同样的问题就是答案。

    在向父模型添加新项时,我只是将这些项作为普通对象推送,父模型如下所示:

    const Parent = new Schema(
      {
        description: { type: String },
        childrenArray: [Object],
      },
      { timestamps: { createdAt: 'created_at' }, collection: 'shopping-lists' }
    );
    

    将此更改为ChildrenModel解决了这个问题,因为现在这些项目被保存为mongoose子文档,我可以使用$operator对其进行操作。

    新架构如下所示:

    const Children = new Schema(
      {
        prop1: { type: String, required: true },
        prop2: { type: String, required: true },
        prop3: { type: String },
      },
      { timestamps: { createdAt: 'createdAt' } }
    );
    
    const Parent = new Schema(
      {
    
        description: { type: String },
        products: [ItemSchema],
    
      },
      { timestamps: { createdAt: 'created_at' }, collection: 'shopping-lists' }
    );
    

    现在,我可以轻松访问以下子文档:

    const { name, isOrdered, author, voterIds, _id, listId } = req.body;
    
    Parent.findOneAndUpdate(
        { _id: listId, 'children._id': _id },
        {
          $set: {
            'children.$.isOrdered': true
          }
        },
        (err, doc) => {
          console.log(doc);
        }
      );
    
        2
  •  0
  •   mzparacha    7 年前

    $ 但是根据mongodb文档,我们不能更新嵌套超过2层的属性数组。简单地说,您不能使用 $ "shoppinglists.$.list.$.products 因此,最好改变数据库的结构,以更好的方式完成它