带有mongoose的Node.js删除一个数组元素

时间:2017-05-16 05:17:11

标签: node.js mongoose

当我点击玉视图页面上的删除按钮时,我试图删除一个数组元素。

点击后,它会将选定的讲师发送为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');
            });
        });

Schema Clist和ilist:

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"
    }]
});

mongodb的一个例子:

{
    "_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
                });     

1 个答案:

答案 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)

});