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

前端 未结 2 1509
长发绾君心
长发绾君心 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:26

    Q: How does mongoose handle adding documents that have fields that are NOT part of the schema?

    The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db. - mongoose docs

    Q: How do you get mongoose to warn you if a specific field of a document hasn't been added even though the document successfully saved?

    The strict option may also be set to "throw" which will cause errors to be produced instead of dropping the bad data. - mongoose docs

    ...but if you absolutely require saving keys that aren't in the schema, then you have to handle this yourself. Two approaches I can think of are:

    1. To save keys that aren't in the schema, you could set strict to false on a specific model instance or on a specific update. Then, you'd need to write some validation that (a) the values in the document conformed to your standards and (b) the document saved in the database matched the document you sent over.

    2. You could see if the Mixed schema type could serve your needs instead of disabling the validations that come with strict. (Scroll down to 'usage notes' on that link, as the link to the 'Mixed' documentation seems broken for the moment.)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题