Created
November 4, 2014 22:27
-
-
Save JayMc/fbf80b0c64cf8a4ca2a3 to your computer and use it in GitHub Desktop.
Mongoose Schema with validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Schema = mongoose.Schema; | |
//validation rule | |
function validator(val){ | |
if(val != 'red'){ | |
return true | |
} | |
return false; | |
} | |
//create Schema | |
var blogSchema = new Schema({ | |
title: { | |
type: String, | |
validate: [validator,'Damn, {PATH} cannot be red.'] | |
}, | |
url: String, | |
subreddit: String, | |
score: Number, | |
thumbnail: String, | |
date: { | |
type: Date, | |
default: Date.now | |
}, | |
comments: [{ | |
body:String, | |
date: Date | |
}] | |
}) | |
blogSchema.statics.random = function(callback){ | |
this.count(function(err, count) { | |
if (err) { | |
return callback(err); | |
} | |
var rand = Math.floor(Math.random() * count); | |
this.findOne().skip(rand).exec(callback); | |
}.bind(this)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment