Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose ODM, change variables before saving

I want to create a model layer with Mongoose for my user documents, which does:

  1. validation (unique, length)
  2. canonicalisation (username and email are converted to lowercase to check uniqueness)
  3. salt generation
  4. password hashing
  5. (logging)

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

like image 865
dev.pus Avatar asked Jul 04 '12 08:07

dev.pus


People also ask

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question. Show activity on this post.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What is pre save in Mongoose?

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.

What is difference between create and save in Mongoose?

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.


3 Answers

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.

like image 56
JohnnyHK Avatar answered Oct 22 '22 15:10

JohnnyHK


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

like image 27
bento Avatar answered Oct 22 '22 17:10

bento


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);
like image 29
Rich Apodaca Avatar answered Oct 22 '22 17:10

Rich Apodaca