簡體   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