Home > database >  Is there a problem with not following the structure of the created model and saving data with differ
Is there a problem with not following the structure of the created model and saving data with differ

Time:03-14

I'm a newbie and I'm doing a backend with nodeJS Express mongoDB.

So I have this model:

const user = new Schema({   

email: String,   

password: String,   

lastName: String,   

firstName: String

})

module.exports = model('User', user);

Then when a user signs Up I save the data :

const createUser = new User({

email: req.body.email,

password: bcrypt.hashSync(req.body.password, 8),

id: req.body.id,

lastName: req.body.lastName,

firstName: req.body.firstName,

photoUrl: req.body.photoUrl,

});

createUser.save((err, user) => {

    if (err) {
        res.status(500).send({message: err});
    }else{
        res.send({message: 'Complete'});
    }
}

So I don't know If when I add new data "photoUrl" that doesn't exist in my main model it could affect the app or with other CRUD functions

CodePudding user response:

Mongoose by default have strict: true flag on schema which basically means that values passed to model constructor that were not specified in the schema do not get saved to the db. So basically all the extra fields passed will be just skipped.

You will have to expicitly disable the strict in order to add the field that is not specified in the DB.

Following example taken from mongoose documentation

// set to false..
const thingSchema = new Schema({..}, { strict: false });
const thing = new Thing({ iAmNotInTheSchema: true });
thing.save(); // iAmNotInTheSchema is now saved to the db!
  • Related