node.js - 猫鼬找到多个文件然后添加对象数组
问题描述
我有以下猫鼬系列
{
"_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 个用户架构
- 用户有多个客户
目标:- 验证用户->选择特定客户->推送条目特定客户的值
- 通过电子邮件 ID 查找用户
- 然后我们在这个用户中有多个客户,所以我想找到特定的 1 个客户和目标条目数组.. 并在条目数组中推送值
例如:- 我想要什么
{
"_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
}
解决方案
所以我会使用 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);
});
类似的东西。
推荐阅读
- java - Jackson:多态反序列化作为子属性
- php - CSS 没有出现在浏览器上
- node.js - CORS 使用 node.js 的 Apollo 服务器中的“Access-Control-Allow-Origin”不能不是通配符“*”
- amazon-web-services - 为 UserData 创建 CloudFormation 堆栈失败
- python - Kaitai Struct:将参数传递给另一个 .kys 文件
- twitter-bootstrap - SASS @use 导入 boostrap 5 scss node_module
- selenium - 使用 Selenium 抓取 Instagram
- django - 如何在 django 中进行计划基础交付并锁定时间和日期
- linux - 如何向 docker 容器添加服务?
- reactjs - 使用 contextAPI TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))