Adding default values to mongoose models at runtime - node.js

I want to have default values for certain fields in my mongoose models. The trick is I don't want to store these values in the database, but what to add them when the model is initialized.
Please help.

You can define an 'init' middleware function for the schema which runs when a model instance is loaded from the database. That should let you manipulate the instance to add your defaults as needed.
Also see this related question for more details as the docs are pretty spare on this.

Maybe a json file?
Using a require('path/to/json' ) you can acces to it and get the values.
Im actually doing something like that, but using the same JSON SCHEMA wich is build for validation purpose.

Related

rapidjson: is it possible to use the Schema tools to generate / output schema?

Ok, what im hoping is possible here is that given an input document with some json in it, I was considering creating a schema document using this json and then output it to a string which I can then use as a reference for future validation. (we have a LOT of json passed around in our software, so creating a schema from what we have will allow me to catch in CI when changes have been made so we can review for privacy violations).
I realise this isn't at all what the schema validator tools are for. but it looks like they do create internally the schema, does anyone have any idea how I might be able to do this?
Thanks

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

MongoDB, Mongoose - what is the best way for adding non-persistent data field to the schema?

I have Mongoose schema and I need to add a non-persistent field to it. The point of this field is to store some status, related to persistent data fields, but without need to store it to the database. I see that some Mongoose alternatives provide such a feature e.g. https://github.com/simpleviewinc/mongolayer#modeladdfieldargs, however I am not able to find similar one inside Mongoose.
Any tip would be greatly appreciated!
In mongoose you have the concept of virtual fields. See doc (http://mongoosejs.com/docs/guide.html#virtuals).
See also related topic at Adding 'virtual' variables to a mongoose schema?

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

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.

Referring to session-based data in a Mongoose virtual attribute

I have a Mongoose model that holds Places. Each place has a lat/lng. I can define a Mongoose virtual attribute called distance that would be used to sort Places in ascending order. What's the best way to refer to the user's location information (let's assume it's stored in a session variable for now) from inside the distance virtual attribute?
For anything involving external data, adding a method to the schema would be a better choice than a virtual property.
I'm solving a similar issue. The problem is that methods are fine if you want perform an operation on a single value but I'm retrieving a list and want to inject a new virtual field into every record in the list - but use session data to generate the field. to do this safely (avoiding globals), I think I'll need to use a QueryStream and inject the new field using an ArrayFormatter that takes the session variables as constructor parameters.
This also looks like a job for LINQ so another approach might be to use one of the ports of LINQ to JS.
If you sill prefer to use virtuals, you can store user location info in NodeJs globals. For example this code may be set after user login:
global.user_location = user.location;

Resources