I want to create a model layer with Mongoose for my user documents, which does:
All of these actions are required to be executed before persisting to the db. Fortunately mongoose supports validation, plugins and middleware.
The bad thing is that I cannot find any good material on the subject. The official docs on mongoosejs.com are too short...
Does anyone have an example about pre actions with Mongoose (or a complete plugin which does all, if it exists)?
Regards
Mongoose save with an existing document will not override the same object reference. Bookmark this question. Show activity on this post.
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
This middleware is defined on the schema level and can modify the query or the document itself as it executed. Today, we're specifically looking at the Pre-save hook. It might be obvious, but a pre-save hook is middleware that is executed when a document is saved.
The . save() is considered to be an instance method of the model, while the . create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.
In your Schema.pre('save', callback)
function, this
is the document being saved, and modifications made to it before calling next()
alter what's saved.
Another option is to use Getters. Here's an example from the website:
function toLower (v) {
return v.toLowerCase();
}
var UserSchema = new Schema({
email: { type: String, set: toLower }
});
https://mongoosejs.com/docs/tutorials/getters-setters.html
var db = require('mongoose');
var schema = new db.Schema({
foo: { type: String }
});
schema.pre('save', function(next) {
this.foo = 'bar';
next();
});
db.model('Thing', schema);
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