In my mongoose model, I have some stats
that are dependent on time. My idea is to add a middleware to change these stats right after the model has been loaded.
Unfortunately, the documentation on the post
-Hooks is a bit lacking in clarity. It seems like I can use a hook like this:
schema.post('init', function(doc) {
doc.foo = 'bar';
return doc;
});
Their only examples involve console.log
-outputs. It does not explain in any way if the doc
has to be returned or if a change in the post-Hook is impossible at all (since it is not asynchronous, there might be little use for complex ideas).
If the pre
on 'init'
is not the right way to automatically update a model on load, then what is?
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
model() Function. The mongoose. model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure.
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
This is how we update models on load, working asynchronously:
schema.pre('init', function(next, data) {
data.property = data.property || 'someDefault';
next();
});
Pre-init is special, the other hooks have a slightly different signature, for example pre-save:
schema.pre('save', function(next) {
this.accessed_ts = Date.now();
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With