nodeJS中的MongoError代码66不可变字段

MongoError code 66 immutable field in nodeJS

我正在尝试执行更新操作。现在我遇到了一个不可变的错误,我知道它是在更新密钥的原因。我想知道,因为我没有从 API 传递 _id,如果我进行控制台,我仍然可以看到 _id。我想从我的对象中删除 _id 以修复此错误。下面的代码

 router.put('/:id', (req, res) => {
    //var findid= req.params.id;
    if (!ObjectId.isValid(req.params.id))
        return res.status(400).send(`No record with given id : ${req.params.id}`);

        var alum = new Alumni({
            fname: req.body.fname,
            lname: req.body.lname,
            contact: req.body.contact,
            gender: req.body.gender,
            dob: req.body.dob,
            message: req.body.message,
            city: req.body.city,
            pincode: req.body.pincode,
            state: req.body.state,
            district: req.body.district,
            password: req.body.password,
            email: req.body.email

    
        });
        //delete alum['_id'];
    Alumni.findByIdAndUpdate(req.params.id, { $set: alum }, { new: true }, (err, doc) => {
        if (!err) { res.send(doc); }
        else { 
            console.log(alum);
            console.log('Error in Alumni Update :' + JSON.stringify(err, undefined, 2)); }
    });
});

我该如何解决这个错误?

每当使用 new Alumni() 等猫鼬模型分配 JSON 对象时,默认情况下它会分配不可变的 _id 字段,因此您不需要将模型与更新对象一起使用。只需按照下面给出的方式分配它

var alum = {
    fname: req.body.fname,
    lname: req.body.lname,
    contact: req.body.contact,
    gender: req.body.gender,
    dob: req.body.dob,
    message: req.body.message,
    city: req.body.city,
    pincode: req.body.pincode,
    state: req.body.state,
    district: req.body.district,
    password: req.body.password,
    email: req.body.email
};