Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Model values after load in Mongoose

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?

like image 312
Lanbo Avatar asked Feb 04 '13 18:02

Lanbo


People also ask

What is Save () in Mongoose?

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.

What is the difference between schema and model in Mongoose?

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.

What does Mongoose model return?

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.

What does REF mean in Mongoose schema?

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.


1 Answers

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();
});
like image 144
hunterloftis Avatar answered Oct 15 '22 03:10

hunterloftis