1

I want to insert a document in my database from a website form. I have a model created with mongoose and I want to save in the database only the attributes that contains data and I don't want to save empty attributes.

This is my model:

const localizationSchema = new Schema({
    name: { type: String, required: true },
    spins: [{ type: String }],
    spinsForChild: [{ type: String }],
    parent: { id: String, name: String },
    localizationType: { type: String },
    count: { type: Number, default: 0 },
    countries: [{ id: String, name: String, cities: [{ id: String, name: String }] }]
});

const Localization = mongoose.model('Localization', localizationSchema);

When I try to save a new document, it creates in the database all attributes although I don't send it on my query.

 Localization.create({
    name: body.name,
    localizationType: body.localizationType,
    "parent.id": parent.id,
    "parent.name": parent.name,
    spins: spins,
    spinsForChild: spinsForChild
}, function(err) {
    if (err) return handleError(err);
    res.redirect('/localizations');
});

This code, for example, inserts in the DB an empty array called "countries".

I tried to use strict: false in the model declaration but it didn't works.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

You could use this answer.

But, thing you try to implement seems to be anti-pattern and can cause errors when you will try to use array update operators with undefined array. So, use it carefully.

Good luck!

ykit9
  • 483
  • 4
  • 7