首页 > 解决方案 > 猫鼬找到多个文件然后添加对象数组

问题描述

我有以下猫鼬系列

{
"_id": "5f494ca2d84e5d2ae800d5a4",
"email": "test@gmail.com",
"customer": [
    {
        "entries": [],
        "payment": [],
        "_id": "5f4950e7f4e0162c2c8af05f",
        "name": "demo",
        "mobile": 8877887788
    },
    {
        "entries": [],
        "payment": [],
        "_id": "5f49514230dc8e3f0063f5e1",
        "name": "demo2",
        "mobile": 8877887788
    },
    {
        "entries": [],
        "payment": [],
        "_id": "5f4956d92d83c03e68905fbb",
        "name": "demo3",
        "mobile": 8877887788
    }
],
"createdAt": "2020-08-28T18:27:46.090Z",
"updatedAt": "2020-08-28T19:27:25.882Z",
"__v": 5

}

例如:- 我想要什么

    {
    "_id": "5f494ca2d84e5d2ae800d5a4",
    "email": "test@gmail.com",
    "customer": [
        {
            "entries": [
                { "amount" : 40 ,
                   "date" : "2020-08-28T19:27:25.882Z"
    }
],


            "payment": [],
            "_id": "5f4950e7f4e0162c2c8af05f",
            "name": "demo",
            "mobile": 8877887788
        },
        {
            "entries": [],
            "payment": [],
            "_id": "5f49514230dc8e3f0063f5e1",
            "name": "demo2",
            "mobile": 8877887788
        },
        {
            "entries": [],
            "payment": [],
            "_id": "5f4956d92d83c03e68905fbb",
            "name": "demo3",
            "mobile": 8877887788
        }
    ],
    "createdAt": "2020-08-28T18:27:46.090Z",
    "updatedAt": "2020-08-28T19:27:25.882Z",
    "__v": 5
    }

标签: node.jsarraysmongoosearraylist

解决方案


所以我会使用 mongoose find by id 来查找用户,然后通过客户数组为每个用户,然后保存您的更改。

  db.<collectionName>.findById(id).then((collection) => {
    collection.customer.forEach((customer, index) => {
        if (customer._id === custId) {
            collection.customer[index] = { ...collection.customer[index], quantity: newQuantity }
        };
    });
    db.<collectionName>.findByIdAndUpdate(id, collection);
}); 

类似的东西。


推荐阅读