2017-02-24 3 views
0

나는 문서 '컬렉션'이의 배열에서 개체를 제거 :몽구스 찾기 및 문서

{ 
name: {type: String, required: true, default: "Untitled Collection"}, 
movies: [ 
     { the_id: {type: String}, 
      movie_id: {type: String}, 
      tmdb_id: {type: String}, 
      original_title: {type: String}, 
       release_date: {type:Date} 
     }], 
author: {type: String},} 

내가 찾아 [] 영화에서 특정 항목을 제거해야합니다. 이것은 내가 현재 가지고있는 것이며 작동하지 않습니다.

req.body는 POST 요청의 데이터를 통해 전달 된 객체이며, 모든 필요한 정보가 현재 않는 모든이 나올 것입니다

Collection.findOne({_id : req.params.id}, (err, collection) =>{ 
     if(err){res.status(400).json(err);} 

     if(!collection) 
     { 
      res.status(404).json({message: 'No collection found'}); 
     }else{ 
      collection.movies.pop(req.body); 
      collection.save(); 

      res.json(collection); 
     } 
    }); 

영화 [] 배열에서 하나와 일치 할 수 있도록이있다 배열의 전면 객체는,하지만 난 당신이 배열에서 항목을 제거 할 수 있습니다

답변

1

$ pull 연산자 살펴보기

collection.movies.pull(req.body); 
0

을 req.body와 동일한 배열의 개체를 제거 할 필요 $pull

Collection.update({ 
    _id: req.params.id 
}, { 
    $pull: { 
     'movies': req.body 
    } 
}, (err, collection) => { 
    if (err) { 
     res.status(400).json(err); 
    } 
    console.log(res); 
    res.status(200); 
});