如何使用ToDeleteItem数组删除多个嵌套对象

时间:2017-07-25 22:08:31

标签: javascript angular

我正在尝试使用核对表从集合中选择位置,并将它们存储到名为ToDelete的数组中:[{_ id:String}]。使用该数组,我想针对Collections对象内部的位置运行它并删除它们。

我将Collection ID存储为param,将数组存储为body。我有控制台记录了数组,所以我知道它有我要删除的ID并正确地将它们传递给服务。

使用mongoose,我的服务器端功能应该是什么样的?这是我最好的尝试。

//DELETE COLLECTION LOCATIONS
collectionRouter.post('removeLocation/:id', function(req, res, next) {
  Collection.update(
    {_id: req.params.id},
    {$pull: {locations: {_id: {$in:req.body}}}},
    function (err, result) {
      if (err) {
        return res.status(500).json({
          title: 'An error occured',
          error: err
        });
      }
      res.status(201).json({
        message: 'Locations Removed',
        obj: result
      });
    });
});

这是我的Collection.Service

removeCollectionLocation(collection: Collection, locations: string[])  {
    let body = locations;
    const headers = new Headers({
      'Content-Type': 'application/json'});
    const token = localStorage.getItem('token')
      ? '?token=' + localStorage.getItem('token')
      : '';
    return this.http.post('http://localhost:3000/collection/removeLocation/' + collection._id + token , body, {headers: headers})
      .map((response: Response)=> response.json())
      .catch((error: Response)=> Observable.throw(error.json()));
  }

谢谢大家。

1 个答案:

答案 0 :(得分:0)

你可以这样做 -

removeCollectionLocation(collection: Collection, locations: string[])  {
    let body = locations;
    const headers = new Headers({
      'Content-Type': 'application/json'});
    const token = localStorage.getItem('token')
      ? '?token=' + localStorage.getItem('token')
      : '';
    return this.http.post('http://localhost:3000/collection/removeLocation/' + collection._id + token , body, {headers: headers})
      .map((response: Response)=> response.json())
      .catch(error => Observable.of(`Bad Promise: ${error}`));
  }