用MongoDB和NodeJS更新Array字段



我是后端新手,试图用NodeJs和MongoDb制作购物车。我尝试了很多方法,但是我无法更新一个产品的数量字段。

这是schema

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
);

最新更新