Skip to content

Instantly share code, notes, and snippets.

@dhodgin
Last active December 26, 2015 22:49
Show Gist options
  • Save dhodgin/7225708 to your computer and use it in GitHub Desktop.
Save dhodgin/7225708 to your computer and use it in GitHub Desktop.
Sample Mongoose Schema for a user
// Sample Mongoose User Schema with a schema plugin
var mongoose = require("mongoose")
, Schema = mongoose.Schema
, lastModified = require("./plugins/lastModified")
, Validator = require("./validator").Validator
, validator = new Validator()
, User;
// define the schema
var schema = new Schema({
email: {
type: String,
validate: validator.isEmail(),
unique: true
},
firstName: {
type: String,
validate: validator.isAlphanumeric()
},
lastName: {
type: String,
validate: validator.isAlphanumeric()
},
parentCompany: {
type: Schema.Types.ObjectId,
ref: "companies"
},
password: {
type: String
},
securityAnswer: {
type: String
},
securityQuestion: {
type: String
}
});
// this plugin is custom and automatically adds
// properties for createdOn, and modifiedOn dates to the schema and can
// be resued for successive model schemas
schema.plugin(lastModified);
schema.methods.changePassword = function(oldPassword, newPassword) {
if (!oldPassword || oldPassword.trim().length === 0) {
return this.invalidate("password", "Old password required");
}
if (!newPassword || newPassword.trim().length === 0) {
return this.invalidate("password", "required");
}
if (oldPassword !== this.password)) {
return this.invalidate("password", "Your old password is incorrect");
}
this.password = newPassword;
};
// an instance method on the model. schema.statics can be used to create static methods
// statics are accesed like: User.myStaticMethod() without instantiating a User object
schema.methods.getCoworkers = function(callback) {
return this.model("users")
.find({ parentCompany: this.parentCompany })
.sort({ email:"asc" })
.exec(callback);
};
// and example of a virtual property that does not persist in the database but can be accessed on user.fullName
schema.virtual("fullName").get(function() {
return this.firstName + " " + this.lastName;
});
// what to do after a save()
schema.post("save", function() {
console.log("saved user " + this.email);
});
User = module.exports = mongoose.model("users", schema);
// what to do on an error
User.on("error", function(err) {
console.log("Error saving user: " + err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment