Mongoose: Schema Enum restriction is not enforced upon updating.

Created on 24 Mar 2014  路  5Comments  路  Source: Automattic/mongoose

Take this schema:

Schema({
status : { type : String, enum : ['active', 'disabled'], default : 'active' }
});

If I attempt to create a document with status field different from active or disabled, then I get an error.
If I attempt to update a document with status field different from active or disabled, then the update will succeed.

Most helpful comment

These days, you can get validation for update() and updateOne() and findOneAndUpdate(), but you have to pass the runValidators option to get it:

    await User.updateOne(
      { _id: userId },
      { status: 'banana' },
      { runValidators: true }
    );

Documented here: http://mongoosejs.com/docs/validation.html#update-validators

All 5 comments

It depends on how you update documents. Middleware will apply only through read -> update -> save circle. It means that if you update your documents by #findOneAndUpdate you update document directly into DB without getting it into client-side. For details see here

Do you plan to support this in save() in the future?

On Fri, Mar 28, 2014 at 3:23 AM, Dmitry M. Lazutkin <
[email protected]> wrote:

It depends on how you update documents. Middleware will apply only through read
-> update -> save circle. It means that if you update your documents by

findOneAndUpdate you update document directly into DB without getting it

into client-side. For details see herehttp://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

Reply to this email directly or view it on GitHubhttps://github.com/LearnBoost/mongoose/issues/1974#issuecomment-38855790
.

These days, you can get validation for update() and updateOne() and findOneAndUpdate(), but you have to pass the runValidators option to get it:

    await User.updateOne(
      { _id: userId },
      { status: 'banana' },
      { runValidators: true }
    );

Documented here: http://mongoosejs.com/docs/validation.html#update-validators

I have the same problem.
mongoose: 5.3.2
schema: (
{ status : { type : String, enum : ['active', 'disabled'], default : 'active' } },
{ strict: 'throw', useNestedStrict: true }
)
method: findOneAndUpdate(query, patch, { runValidators: true })

@fataltrace please open up a separate issue with detailed code samples. Make sure you read the update validator docs carefully first.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ArThoX picture ArThoX  路  3Comments

p3x-robot picture p3x-robot  路  3Comments

Igorpollo picture Igorpollo  路  3Comments

varunjayaraman picture varunjayaraman  路  3Comments

jeneser picture jeneser  路  3Comments