繁体   English   中英

array.splice()在猫鼬中无法正常工作

[英]array.splice() is not working properly in mongoose

我正在使用splice和findOne()来删除嵌套元素。

这是我的JSON数据

     "username" : "xyz",
    "ProductInCart" : [
            {
                    "id" : ObjectId("5a533a0a6a0207023b8e30d3"),
                    "ProductImage" :"",
                    "Title" : "Model Green",
                    "Price" : 399,
                    "_id" : ObjectId("5a53667774d601028b9cb43f")
            },
            {
                    "id" : ObjectId("5a533a0a6a0207023b8e30d3"),
                    "ProductImage" :"",
                    "Title" : "Model Green",
                    "Price" : 399,
                    "_id" : ObjectId("5a53667b74d601028b9cb440")
            }

这是我的删除路线

    router.delete('/cart/remove/:ordername/:id',function(req,res){

 var ProductId = req.params.id;
 var OrderName = req.params.ordername; 

User.findOne({id:req.user._id},function(err,user){
if (err) {
throw err;
} else {  
  user.ProductInCart[OrderName].splice(ProductId,1);
  user.save();
  res.redirect("back");
}
})       
})

这将在命令行中返回以下错误

TypeError:无法读取null的属性“ ProductInCart”

我在这里想念什么?

您正在收到错误,因为在拼接之前参考的位置未定义。 传入的“ user.ProductInCart [OrderName]”不是对ProductsInCart数组中任何对象的有效引用。

代码正在查看该位置,并将值作为ProductCart属性上的OrderName传递。 通过阅读代码,我的假设是您将传递产品名称,而不是将数组位置作为OrderName。 在这种情况下,您需要在使用接头之前搜索ProductsInCart数组以找到正确的位置。

作为一般说明,最好在引用嵌套属性之前执行空检查-在这种情况下,请考虑以下代码。

if (user.ProductInCart && user.ProductInCart[OrderName]) {
   user.ProductInCart[OrderName].splice(ProductId,1);
   user.save();
}

这里是它的替代解决方案(不使用.splice())

   router.delete('/cart/remove/:ordername/:id',function(req,res){

     User.update({_id:req.user._id},{ $pull:{ProductInCart:
         {_id:req.params.id}}},function(err,deleted){
               if (err) {
                console.log(err)
               } else {
      res.redirect("back");
      }
    })  
  })

暂无
暂无

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

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