2017-07-19 5 views
0

データベース内のオブジェクトとオブジェクトの配列の説明が多数あります:['red'、 'blue'、 'green']、paramsが配列の項目である場合、データベース内のidオブジェクトの検索方法

userFactory.deleteDescription = function(description) { 
    return $http.delete('/api/editProduct/' + description) 
} 

API

router.delete('/editProduct/:description', function(req, res){ 
    var editProduct = req.params.id; 
     Product.findOneAndUpdate({ _id: editProduct }, { $pull: { description: req.params.description }}, function(err, product){ 
      if(err) throw err; 
      if(!product){ 
       res.json({ success: false, message: 'no product' }); 
      } else { 
       product.update(function(err){ 
        if(err){ 
         console.log(err); 
        } else { 
         res.json({ success: true, message: 'ok!'}) 
        } 
       }); 
      } 
     }); 
}); 

コントローラ

app.removeDescription = function(description){ 
    User.deleteDescription(description).then(function(data){ 
     if(data.data.success) { 
      console.log('removed') 
     } else { 
      app.showMoreError = data.data.message; 
      console.log('bad') 
     } 
    }) 
} 
:私は配列 工場でオブジェクトを発見req.paramsを使用しているため、データベース内のIDオブジェクトによってT見つけます

Quesstion:使用する場合、オブジェクトの_idを正しく取得する方法req.params.description配列からアイテムを取得しますか?私が手作業で_id: '...'を書いた場合、すべてがうまくいく。

答えて

0

申し訳ありませんが、もう一度お試しください。 req.paramsには、名前付きのルーティングされたパラメータが含まれています。私があなたを正しく理解していれば、対応する説明のオブジェクトを見つけてその説明を削除したいと考えています。ただし、配列をreturn $http.delete('/api/editProduct/' + description)に渡すことはできません。したがって、パラメータとして渡すことができ、_idを必要とせずに、フィルタとしての説明とともにfindOneAndUpdateメソッドを使用します。だから、あなたが/ editProduct /に競合するルートを持っていないことを確認してください

userFactory.deleteDescription = function(description) { 
    return $http.delete('/api/editProduct/', description) 
} 

router.delete('/editProduct/', function(req, res){ 
    Product.findOneAndUpdate({ description: req.body }, { $pull: { description: req.body }}, function(err, product){ 
     if(err) throw err; 
     if(!product){ 
      res.json({ success: false, message: 'no product' }); 
     } else { 
      product.update(function(err){ 
       if(err){ 
        console.log(err); 
       } else { 
        res.json({ success: true, message: 'ok!'}) 
       } 
      }); 
     } 
    }); 
}); 

のようなものがあるかもしれません。

+0

はい、しかしreq.body._idは定義されていません –

+0

@ V.Rええ、ごめんなさい。私はいくつかのより良い情報で私の答えを更新しました。 – John

+0

これは工場では '/ api/editProduct /'を1回だけ使用できますか? –

関連する問題