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.
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 byfindOneAndUpdate 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.
Most helpful comment
These days, you can get validation for
update()
andupdateOne()
andfindOneAndUpdate()
, but you have to pass therunValidators
option to get it:Documented here: http://mongoosejs.com/docs/validation.html#update-validators