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

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 with a field NOT defined in the schema. Instead, it created a new document in the collection but without the field. (Note: I realize mongodb itself is "schema-less" so each document in a collection can be completely different from each other.)
two questions
How does mongoose handle adding documents that have fields that are NOT part of the schema? It seems like it just ignore them, and if none of the fields map, will create an empty document just with an ObjectId.
And 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 question is - I believe - simple enough, so I didn't add code, but I definitely will if someone requests.)
Thanks.

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.)

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.

Related

CouchDB check if a document exists in a validation function

I would like to see if a document exists in the database that has the name field "name" set to "a name" before allowing a new document to be added to the database.
I this possible in CouchDB using update handlers (inside design documents)?
Seems you are looking for a unique constraint in CouchDB. The only unique constraint supported by CouchDB is based on the document ID.
You should include your "name" attribute value into the document ID if you would like to have the document unicity based on it.
Validate document update functions defined in desing documents can only use the data of the document being created/updated/deleted, it can no use data from other documents in the database.
Yo can find a similar question here.
This is not widely known, but _update endpoint allowed to return a doc with _id prop different from requested. It means, in your case, you need to have an unique document say _id:"doc-name", which will serve as a constraint.
Then you call smth like POST _design/whatever/_update/saveDependentDoc/doc-name, providing new doc with different _id as a request body.
Your _update function will effectively receive two docs as an input (or null and newDoc if constraint doc is missing). The function then decides what should it do: return received doc to persist it, or return nothing.
The solution isn’t a full answer to your question, however it might be helpful in some cases.
This trick only works for updating existing docs if you know revision, for sure.

Mongoose: Remove Document and all references completely

I was wondering. I have a lot of coding to do with a function to remove a document from the database. Basically removing just the object is not that much work, but removing the _id reference from all the other models step by step in the right order is the big work load (I pushed the object ID into the other objects so I could create relations and populate later).
I was wondering: is there no function standard in mongoose that instantly removes the document as well as all its objectId references in the documents of the other model types (so completely remove the object and all it's ObjectID references in all the other collections in the DB)?
You can achieve what you are looking for using this NPM package called
cascading-relations here

Saving a form part way through mongodb

I'm pretty new to MongoDB and best practices. I'm using Node full stack JS.
I created a form which spans multiple screens. This saves to a mongoose.model Schema and creates a document when the user submits the form.
I've been given the requirement to allow the user to save the form when part way through. The problem with trying to save to the existing Schema is I get a duplicate id reference error as I'm saving multiple fields as null which already exist in the Collection. Plus I'm thinking this is a waste of memory.
The answer is very simple it just took me some circular thinking to get to it. I check to see if properties are undefined before setting them. If they are undefined they are an empty value rather than null i.e. {} for an Object. Mongoose is ok with that, it just doesn't like null values (makes sense).

How can I make mongoose to validate an entire 'outdated' MongoDB collection?

during the development of my app, i very often add custom and new fields to an existing schema, making the 'old' content in my mongodb 'incompelete' and missing the new fields. this leads sometimes to null content where it's required and it's in my use case very bad.
my question is what command/utility do i need to use to make mongoose validate my old documents, and in potential add those missing fields with pre-defined defaults to the old documents?
i remember reading something about that kind of functionality when i started learning how to use mongoose, but i just can't find it anywhere anymore..
thanks in advance :)
Amit

Why by default all fields in mongoose are not required?

It seems that the default value of the required attributes of each field in mongoose schema is false. So, if I save any documents, those not required fields are not written into DB at all. I was wondering why this is designed in this way, and how I can change the default value to be true for all fields.
Thanks,
Following the documentation required has nothing to do with writing into the database (especially if it is false). It switches the field validation on or off. Default is off.
There must be another reason why your fields are not persisted.

Resources