2016-10-20 5 views
0

クラスからレッスンを削除できる削除ボタンを設定しようとしています。 $ pullを使うとlesson_idがnullに設定されているようです。その要素を完全に削除する方法はありますか?

例えば
var classSchema = new Schema({ 
    title: { type: String, required: true }, 
    lessons: [{ 
     _id: false, 
     lesson_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Lesson'} 
    }] 
}); 

module.exports.deleteLesson = function(class_id, lesson_id, callback){ 
    Class.update(
     {'_id': class_id}, 
     { $pull: {lessons: {'lesson_id.$._id': lesson_id}}}, 
     callback 
    ) 
} 

{ _id: 5808, 
    title: 'cd', 
    __v: 0, 
    lessons: [ { lesson_id: [Object] }, { lesson_id: [Object] } ] } 

あなたが(配列)の教訓から要素を削除する必要がある場合は、あなただけの要素の削除を実行する必要が

{ _id: 5808, 
    title: 'cd', 
    __v: 0, 
    lessons: [ { lesson_id: null }, { lesson_id: [Object] } ] } 
+0

多分これは私が代わりにpullAllあなたは、{$を使用しているものならばそのように使用する必要があり、$がこのケースで正しい演算子であるとは思わないhttp://stackoverflow.com/a/20275454/2931650 – Roshan

+0

を助けるかもしれませんプル:{lesson:{'lesson_id._id':lesson_id}}}または勘違い{$ pull:{lesson:{'lesson_id':lesson_id}}}? –

答えて

0

なり配列から削除し、保存操作を実行します。私は同様のアプローチを示すコードを書いています。

Class.findOne({ _id: class_id }, function(err, cls) { 

      # Delete the element (for example, using underscore) 
      cls.lessons = _.without(cls.lessons, class_id); 

       cls.save(function (err) {  
         callback(err); 
      }); 
    }); 
関連する問題