John Yaghobieh
John Yaghobieh

Reputation: 131

MongoError: After applying the update to the document

I need some help.

I'm trying to make post req to this route:

router.post('/admin/editFront', isLoggedIn, (req, res, next) => {
    req.checkBody('title', 'Title is require').notEmpty();
    req.checkBody('aboutUs', 'About us section is require').notEmpty();
    req.checkBody('email', 'Check email again').notEmpty().isEmail();

    let errors = req.validationErrors();
    if(errors) {
        req.flash('error_msg', errors.msg);
        console.log(errors);
    }

    let cube = ({
        title: req.body.cubeTitle,
        img: req.body.cubeImg,
        info: req.body.cubeInfo
    })

    let front = new FrontInfo();
    front.title = req.body.title;
    front.aboutUs = req.body.aboutUs;
    front.email = req.body.email;
    front.phone = req.body.phone;
    front.cube.push(cube);
    // front.socialNet.push(req.body.social);

    console.log(front);

    FrontInfo.findOneAndUpdate({email: req.body.email}, front, { upsert: true }, (err, doc) => {
        if(err) console.log(err);
        else {
            req.flash('success', doc);
            res.redirect('/editFront');
        }
    });
});

Here is my Schema:

let cube = new Schema({ 
    title: { type: String },
    img: { type: String },
    info: { type: String }    
});

let socialNet = new Schema({
    title: { type: String, required: true },
    link: { type: String, required: true },
    icon: { type: String, required: true }
});

let FrontInfo = new Schema({
    title: { type: String, required: true },
    aboutUs: {type: String, required: true},
    phone: {type: String, minlength: 9, required: true},
    email: {type: String, required: true},
    cube: {type: [cube], default: []},
    updateDate: {type: Date, default: Date.now}
});

So, if I try to create a new Schema it works. But if I try to update the new one I get this error:

enter image description here

I spent a long time trying to fix it! Please help me friends

Upvotes: 1

Views: 5523

Answers (1)

Mika Sundland
Mika Sundland

Reputation: 18939

When you use let front = new FrontInfo(); you are creating a new document that has its own _id. This _id is different from the _id of the document that you're updating. You are not allowed to update the _id field, which is why you get the error message

the (immutable) field '_id' was found to have been altered to _id

So instead of creating a new Mongoose document you should just create a new ordinary Javascript object instead:

let front = {};
front.title = req.body.title;
front.aboutUs = req.body.aboutUs;
front.email = req.body.email;
front.phone = req.body.phone;
front.cube = [];
front.cube.push(cube);

This only contains the fields that you've listed.

Upvotes: 4

Related Questions