【问题标题】:mongoose find multiple fileds then add array of object猫鼬找到多个文件然后添加对象数组
【发布时间】:2020-08-30 01:22:41
【问题描述】:

我有以下猫鼬收藏

{
"_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

}

  • 我们有多个用户上面这只是 1 个用户架构

    • 用户有多个客户

    目标:- 验证用户 -> 选择特定客户 -> 在特定客户中推送条目值

    1. 通过电子邮件 ID 查找用户
    2. 然后我们在这个用户中有多个客户,所以我想找到特定的 1 个客户并定位 entries 数组 .. 并将值推送到条目数组

例如:- 我想要什么

    {
    "_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.js arrays mongoose arraylist


【解决方案1】:

所以我会使用 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);
}); 

类似的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 2019-03-28
    • 2017-12-22
    • 2021-06-07
    • 2014-01-14
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    相关资源
    最近更新 更多