How does `mongoose` handle adding documents that have FIELDS that are __NOT__ part of the schema?

前端 未结 2 1539
长发绾君心
长发绾君心 2021-02-07 00:04

I\'m playing around with quick start guide for mongoose.

http://mongoosejs.com/docs/index.html

I assumed that it would throw an error when I saved a document wi

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 00:27

    Mongoose lets you add "validator" and "pre" middleware that perform useful functions. For instance, you could specify the required attribute in your schema to indicate that a specific property must be set. You could also specify a validator that you can craft to throw an error if the associated property doesn't meet your specifications. You can also set up a Mongoose "pre" validator that examines the document and throws an Error if it finds fields that are outside of your schema. By having your middleware call next() (or not), you can control whether you proceed to the document save (or not).

    This question/response on stackoverflow can help with figuring out whether or not an object has a property.

提交回复
热议问题