将对象添加到对象数组,Nodejs,猫鼬

时间:2019-01-29 19:18:45

标签: node.js express mongoose

我正在开发一个小型应用程序,您可以在其中将产品添加到用户购物车中。

我设置了将指定产品添加到购物车的路线,并且效果很好。但是,当我添加它时,显示在数组中的只是产品的_id,而我正在寻找的是包含某些信息(即产品名称,产品价格等)的对象。这样我以后可以在我的React-Redux App中访问它。我在网上找到了一些建议,但它们似乎根本不适合我,或者给了我与我相同的东西。

此处路线:

Cart.findOne({ user: req.user.id })
      .then(cart => {
        Product.findById(req.params.product_id).then(product => {
          const newItem = {}
          newItem._id = product._id; 
          newItem.name = product.name;
          newItem.price = product.price;
          const total =
            parseFloat(cart.total) + parseFloat(product.price);
          cart.total = Math.round(total*100)/100;


          cart.items.push(newItem);
          cart.save().then(cart=> res.json(cart));
        });
      })
      .catch(err => res.status(404).json(err));
  })
  .catch(err => res.status(404).json(err));

以下是相应的架构:

        const CartSchema = new Schema({
      user: {
        type: Schema.Types.ObjectId,
        ref: "users"
      },
      total: {
        type: String,
        default: 0
      },
      items: [
        {
          product: {
            type: Schema.Types.ObjectId,
            ref: "product"
          }
        }
      ]
    });

任何帮助将不胜感激。 谢谢

2 个答案:

答案 0 :(得分:0)

尝试按原样传递产品。也许是由于该模式,猫鼬希望使用Product,而不是newItem

这样的通用对象
Cart.findOne({ user: req.user.id }).then(cart => {
  return Product.findById(req.params.product_id);
}).then(product => {
  const total = parseFloat(cart.total) + parseFloat(product.price);
  cart.total = Math.round(total*100)/100;
  cart.items.push(product);
  return cart.save();
}).then(cart => {
  return res.json(cart)
}).catch(err => res.status(404).json(err));

注意:我也修复了您的Promise链结构。这样,您就避免了回调地狱,并且整个承诺链只需要一个catch语句。

答案 1 :(得分:0)

怎么样

const CartSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: "users"
    },
    total: {
        type: String,
        default: 0
    },
    items: [
        {
            type: Schema.Types.ObjectId,
            ref: "product"
        }
    ]
});

推送到项目数组中的项目应该是Product的实例,而不仅仅是普通对象。

相关问题