繁体   English   中英

搜索对象数组以匹配 mongodb 中的 objectId

[英]Search an array of objects to match objectId from mongodb

我正在尝试通过包含用于填充的嵌套对象 id 的键来搜索对象数组。

我的对象


{
  service: 'user',
  isModerator: true,
  isAdmin: true,
  carts: [
    {
      _id: 5e1344dcd4c94a1554ae0191,
      qty: 1,
      product: 5e09e4e0fcda6f268cefef3f,
      user: 5e0dda6d6853702038da60f0,
      expireAt: 2020-01-06T14:31:56.708Z,
      __v: 0
    },
    {
      _id: 5e13455306a54b31fc71b371,
      qty: 1,
      product: 5e09e507fcda6f268cefef40,// object ID
      user: 5e0dda6d6853702038da60f0,
      expireAt: 2020-01-06T14:33:55.573Z,
      __v: 0
    },
  ],

我想匹配购物车数组是否包含用户正在添加的产品的购物车,而不是第二次添加它,而是增加现有产品的数量。


我的代码

  const itemId = req.body._id;
  const userId = req.user._id;
  const { qty } = req.body;
  try {
    const producto = await Product.findById(itemId);
    const user = await User.findById(userId).populate({
      path: 'carts',
    });
    const result = user.carts.find((o) => {
      console.log(typeof o.product) // returns object
      console.log(typeof producto._id); // returns object
      return o.product === producto._id
    });
    console.log(result); // returns undefined
    if (result !== undefined) {
      const foundCart = await Cart.findById(result._id);
      foundCart.qty += qty;
      await foundCart.save();
      return res.json({ message: 1 });
    }
    const newCart = new Cart({
      qty,
      product: producto,
      user,
    });
    const cart = await newCart.save();
    user.carts.push(cart);
    await user.save();
    return res.json({ message: 1 });
  } catch (error) {
    return console.log(error);
  }

我认为问题是这条线

  return o.product === producto._id

你能像这样改变它并尝试吗?

  return o.product.toString() === producto._id.toString()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM