Skip to content

Instantly share code, notes, and snippets.

@AndyNovo
Last active August 29, 2015 14:24
Show Gist options
  • Save AndyNovo/80c0d57be80df0ca884f to your computer and use it in GitHub Desktop.
Save AndyNovo/80c0d57be80df0ca884f to your computer and use it in GitHub Desktop.
Simple Mongoose Schema
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/schematest');
var animalSchema = new mongoose.Schema({
type: {type: String, required: true},
age: Number,
lastInspected: {type: Date, default: Date.now},
name: {type: String, required: false}
});
animalSchema.methods.makeNoise = function(callback){
var noise = "Some animals make noise";
if (this.type == "Giraffe"){
if (this.age < 2){
noise = "Young giraffes can make a honking kind of sound.";
} else {
noise = "Elder giraffes do not make noise.";
}
}
callback(noise);
};
animalSchema.statics.findBabies = function(callback){
this.find({age: {$lt: 2}}, callback);
};
var Animal = mongoose.model('Animal', animalSchema);
var babyGiraffe = new Animal({ type: "Giraffe", age: 0});
babyGiraffe.save(function(err, baby){
if (err) {
console.log("Error: ",err);
} else {
console.log(baby);
Animal.findBabies(console.log);
baby.makeNoise(console.log);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment