node.js - 使用 MongoDB 和 NodeJS 更新数组中的字段
问题描述
我是后端新手,正在尝试使用 NodeJs 和 MongoDb 制作购物车。我尝试了很多东西,但我无法更新产品的数量字段。
这是架构
const mongoose = require('mongoose');
const itemsSchema = mongoose.Schema(
{
prodId: String,
name: String,
price: Number,
qty: {
type: Number,
default: 1,
min: 1,
},
},
{
timestamps: true,
}
);
const cartSchema = mongoose.Schema(
{
total: {
type: Number,
},
products: [itemsSchema],
},
{
timestamps: true,
}
);
const Cart = mongoose.model('carts', cartSchema);
module.exports = Cart;
这是控制器
const Cart = require('../models/cart');
exports.postItemToCart = async (req, res) => {
const { prodId } = req.body;
Cart.updateOne(
{ 'products.prodId': prodId },
{ $inc: { 'products.qty': 1 } }
);
return res.status(200).send(Cart);
};
这是购物车
[
{
_id: '60062c7a9b0bfd350b3eb755',
__v: 3,
createdAt: '2021-01-19T00:48:58.006Z',
products: [
{
qty: 1,
_id: '6006333bd00fe96af648d308',
prodId: '1111',
name: 'Product One',
price: 24.22,
updatedAt: '2021-01-19T01:17:47.034Z',
createdAt: '2021-01-19T01:17:47.034Z',
},
{
qty: 1,
_id: '600634337f3eba6b451a26e5',
prodId: '2222',
name: 'Product Two',
price: 24.22,
createdAt: '2021-01-19T01:21:55.417Z',
updatedAt: '2021-01-19T01:21:55.417Z',
},
],
total: 48.44,
updatedAt: '2021-01-21T02:19:49.955Z',
},
];
我可以在 Mongoose 文档控制台中更改和更新,但我不能在我的项目中应用相同的代码。
请帮忙 :)
解决方案
positional operator
将帮助您更新第一个匹配的数组元素。
Cart.updateOne(
{ 'products.prodId': prodId },
{ $inc: { 'products.$.qty': 1 } } //note dollar sign
);
推荐阅读
- networking - 从 WLAN 中继器到基站路由器的网络打印机反射
- box - 将文件上传到 Box 时出现格式错误的流
- excel - VBA - 粘贴事件和撤消粘贴的最后一个动作
- php - $oQueryBuilder->getQuery()->getResult() 的问题
- python - Python脚本关闭时结束执行子进程
- c++ - 复数相除 - 条件
- android - 我可以在 android studio 的片段上使用 Firebase 吗?
- sorting - 获得shell排序通过次数的公式是什么?
- unity3d - Unity 在鼠标点处实例化对象得到错误的坐标
- c# - 在不知道结构的情况下使用 Newtonsoft.Json 解析 JSON