为什么我的 Mongoose 更新找不到匹配项?

vc9ivgsu  于 11个月前  发布在  Go
关注(0)|答案(2)|浏览(140)

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

{
"_id": {
  "$oid": "6555453298c59137f9cb2ee5"
},
"userId": {
  "$oid": "6555453298c59137f9cb2ee3"
},
"email": "[email protected]",
"items": [
  {
    "quantity": 3,
    "product": {
      "$oid": "655437995bc92c0647deb512"
    },
    "_id": {
      "$oid": "65555277fe01541a2052bd5f"
    }
  },
  {
    "quantity": 1,
    "product": {
      "$oid": "655437995bc92c0647deb513"
    },
    "_id": {
      "$oid": "65555278fe01541a2052bd65"
    }
  }
}

字符串
在items数组中,我想将数量增加1,其中product(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 [email protected])

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.

guz6ccqo

guz6ccqo1#

更改updateOne查询以直接匹配productId

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

字符串
或者,您可以使用findOneAndUpdatenew选项来直接检索更新的cart

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

gcxthw6b

gcxthw6b2#

@eekinci的答案是正确的,它将通过$更新items数组中的第一个匹配元素,假设product值是唯一的。
对于当前使用arrayFilters的实现,必须应用过滤后的位置运算符$[<identifier>]

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

字符串
Demo @ Mongo Playground

相关问题