我的购物车Collection 中有以下文档:

{
"_id": {
  "$oid": "6555453298c59137f9cb2ee5"
},
"userId": {
  "$oid": "6555453298c59137f9cb2ee3"
},
"email": "aaaaaa@aaa.com",
"items": [
  {
    "quantity": 3,
    "product": {
      "$oid": "655437995bc92c0647deb512"
    },
    "_id": {
      "$oid": "65555277fe01541a2052bd5f"
    }
  },
  {
    "quantity": 1,
    "product": {
      "$oid": "655437995bc92c0647deb513"
    },
    "_id": {
      "$oid": "65555278fe01541a2052bd65"
    }
  }
}

在Items数组中,我希望将数量增加1,其中产品(ProductID)=655437995bc92c0647deb512.我的增加函数如下:

exports.increaseProductQuantity = async (req, res) => {
console.log('user.service increaseProductQuantity')
const {productId} = req.body;
console.log('productIdd', productId)
const email = authenticateToken(req, res)

console.log('increaseProductQuantity email', email)
(increaseProductQuantity email logs aaaaaa@aaa.com)


try {
    await Cart.updateOne({
        "email": email
    }, {
        "$inc": {
            "items.$.quantity": 1
        }
    }, {
        "arrayFilters": [{
            "items.product": productId
        }]
    })

    const cart = await Cart.findOne({
        email: email,
    }).populate({
        path: 'items.product',
        model: 'Products'
    })

    console.log('cart', cart)

    // const newCart = JSON.parse(JSON.stringify(cart));
    // newCart.cartTotal = computeCartTotal(newCart);
    // console.log('newCart', newCart)

    // res.status(201).json(newCart)
} catch (error) {
    console.error(error);
    return res.status(500).send('Problem changing item quantity.')
}

}

我得到的错误是:

MongoServerError: The positional operator did not find the match needed from the query.

推荐答案

将您的updateOne查询更改为直接与productId匹配:

await Cart.updateOne(
  {
    "email": email,
    "items.product": productId
  },
  {
    "$inc": {
      "items.$.quantity": 1
    }
  }
);

或者,您可以使用带有new选项的findOneAndUpdate直接检索更新后的cart:

const cart = await Cart.findOneAndUpdate(
  { "email": email, "items.product": productId },
  { "$inc": { "items.$.quantity": 1 } },
  { new: true, populate: { path: 'items.product', model: 'Products' } }
);

Mongodb相关问答推荐

如何使用mongodb进行离线开发?

MongoDb聚合查询问题

如何在 kubernetes 中获取分片 mongodb 的备份

Mongo按最大分组排序

查询有关 Go 项目中对象数组的 MongoDb 集合

MongoDB 存储大量指标/分析数据的方法

MongoError:$subtract 累加​​器是一元运算符

Meteor 中的平均聚合查询

从 PHP 打印 MongoDB 日期

根据 Month 删除 mongodb 中的旧记录

使用 Spring Boot >= 2.0.1.RELEASE 将 ZonedDateTime 保存到 MongoDB 时出现 CodecConfigurationException

mongo php副本连接非常慢

嵌套在文档数组中的mongodb展开数组

Mongoose.js 通过一个 connect() 调用创建到 MongoDB 的多个连接

如何使用 MongoDB 和 Mongoid 在 Rails 3 上进行适当的数据库测试 (TDD)

在 MongoDB 中合并两个集合

$orderby 和 Sort 之间的 MongoDB 区别

没有参考选项的mongoose填充字段

MongoDB 查询:字段不存在或具有特定值

MongoDB备份计划