2017-05-16 52 views
0

我想刪除一個數組元素,當我點擊玉視圖頁上的刪除按鈕。Node.js與貓鼬刪除一個數組元素

點擊後,它將發送選定的教師作爲req.body反對。

在服務器端,它會找到包含教師objectId的課程。

對我而言有什麼想法?

謝謝您的閱讀。

這裏是我的代碼:

var id = req.body._id; 
clist.find({ instructors: { $in: [id] } }).exec(function (err, result) { 
      result.forEach(function (obj) { 
       clist.update(
        { _id: new mongoose.Types.ObjectId(obj._id)}, 
        { $pull: { instructors : [new mongoose.Types.ObjectId(id)] } } 
       ); 
       console.log(new mongoose.Types.ObjectId(obj._id) + ' was deleted'); 
      }); 
     }); 

架構CLIST和i列表:

MongoDB的
var instructorlist = mongoose.Schema({ 
    name: { type: String, required: true }, 
    age: { type: Number, required: true }, 
    gender: { type: String, required: true }, 
    DOB: { type: Date, required: true, default: Date.now }, 
    email: { type: String, required: true }, 
    phone: { type: Number, required: true }, 
    address: { type: String, required: true }, 
    dateofstart: { type: Date, required: true}, 
    courses: [{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "clist" 
    }] 
}); 
var courselist = mongoose.Schema({ 
    coursename: { type: String, required: true }, 
    coursenumber: { type: String, required: true }, 
    coursecredit: { type: Number, required: true }, 
    courseroom: { type: String, required: false }, 
    courseregisteddate: {type: Date, default: Date.now}, 
    students: [{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "slist" 
    }], 
    instructors: [{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "ilist" 
    }] 
}); 

一個例子:

{ 
    "_id": { 
     "$oid": "591a7a3b391a1842e8a69e23" 
    }, 
    "coursename": "JDKD", 
    "coursenumber": "COMP4483", 
    "coursecredit": 4, 
    "courseroom": "sdaf", 
    "instructors": [ 
     { 
      "$oid": "591a374422a3a13d38c0bbe5" 
     } 
    ], 
    "students": [], 
    "courseregisteddate": { 
     "$date": "2017-05-16T04:04:11.848Z" 
    }, 
    "__v": 0 
} 

當我加入教練的objectID在課程。

var newcourse = new clist({ 
        'coursename': req.body.coursename, 'coursenumber': req.body.coursenumber, 'coursecredit': req.body.coursecredit 
        , 'courseroom': req.body.room, 'instructors': instructors._id 
       });  
+0

你能張貼什麼成爲「CLIST」模式的架構? – Paul

+0

@Paul我更新了我的貼子。 –

+0

爲什麼你在那裏使用循環? –

回答

1

使用相同的操作來查找和更新多個

clist.update(
    { instructors: { $in: [id] }}, 
    { $pull: { instructors : { _id : new mongoose.Types.ObjectId(id) } } }, //or{ $pull: { instructors: mongoose.Types.ObjectId(id) } } 
    { 
    multi:true 
}, 
function(error, success){ 
    if(error){ 
    console.log("error",error) 

} 
console.log("success",success) 

}); 
+0

成功{OK:1, n修改:0, N:2, OPTIME: {TS:時間戳{_bsontype: '時間戳',low_:3, high_:1494912734}, t:1}, electionId:7fffffff0000000000000001} –

+0

但在選定的課程中仍然存在教師ID .. –

+0

非常感謝。我會嘗試! –