Last active
August 29, 2015 14:24
-
-
Save AndyNovo/80c0d57be80df0ca884f to your computer and use it in GitHub Desktop.
Simple Mongoose Schema
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 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