Mongoose Schemas
Basic Schema
A basic User Schema:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
name: String,
password: String,
age: Number,
created: {type: Date, default: Date.now}
});
var User = mongoose.model('User', userSchema);
Schema methods
Methods can be set on Schemas to help doing things related to that schema(s), and keeping them well organized.
userSchema.methods.normalize = function() {
this.name = this.name.toLowerCase();
};
Example usage:
erik = new User({
'name': 'Erik',
'password': 'pass'
});
erik.normalize();
erik.save();
Schema Statics
Schema Statics are methods that can be invoked directly by a Model (unlike Schema Methods, which need to be invoked by an instance of a Mongoose document). You assign a Static to a schema by adding the function to the schema’s statics
object.
One example use case is for constructing custom queries:
userSchema.statics.findByName = function(name, callback) {
return this.model.find({ name: name }, callback);
}
var User = mongoose.model('User', userSchema)
User.findByName('Kobe', function(err, documents) {
console.log(documents)
})
GeoObjects Schema
A generic schema useful to work with geo-objects like points, linestrings and polygons. Both Mongoose and MongoDB support Geojson.
Example of usage in Node/Express:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Creates a GeoObject Schema.
var myGeo= new Schema({
name: { type: String },
geo : {
type : {
type: String,
enum: ['Point', 'LineString', 'Polygon']
},
coordinates : Array
}
});
//2dsphere index on geo field to work with geoSpatial queries
myGeo.index({geo : '2dsphere'});
module.exports = mongoose.model('myGeo', myGeo);
Saving Current Time and Update Time
This kind of schema will be useful if you want to keep trace of your items by insertion time or update time.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Creates a User Schema.
var user = new Schema({
name: { type: String },
age : { type: Integer},
sex : { type: String },
created_at: {type: Date, default: Date.now},
updated_at: {type: Date, default: Date.now}
});
// Sets the created_at parameter equal to the current time
user.pre('save', function(next){
now = new Date();
this.updated_at = now;
if(!this.created_at) {
this.created_at = now
}
next();
});
module.exports = mongoose.model('user', user);