首页 > 解决方案 > 使用 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 文档控制台中更改和更新,但我不能在我的项目中应用相同的代码。

请帮忙 :)

标签: node.jsmongodbmongoose

解决方案


positional operator将帮助您更新第一个匹配的数组元素。

Cart.updateOne(
    { 'products.prodId': prodId },
    { $inc: { 'products.$.qty': 1 } } //note dollar sign
  );


推荐阅读