NodeJS Mongoose Schema
MongoDB + Mongoose
About Mongoose : Guide
This post is based on Official Guide of Mongoose
Definition Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blog = new Schema({
title: String, // key: type general text
author: String,
body: String,
comments: [{ body: String, date: Date }], // Array
date: { type: Date, default: Date.now }, // type and default
hidden: Boolean,
meta: {
votes: Number,
favs: Number // hash?
}
});
required : Same as database not null
var s = new Schema({ name: { type: String, required: true });
Schema Type
Support Type : Official Guide
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
Schema instance methods
We can add instance method against Schema. It’s javascript feature.
var modelSchema = new Schema({name: String, type: String });
modelSchema.methods.findByType = function(typeattr) {
return this.model('Model').find({ type: this.type }), typeattr);
}
var iModel = mongoose.model('Model', modelSchema); // All operations in model
var a = new iModel({ type: 'aclass' });
a.findByType(function (err, models) { // Use in model
console.log(models);
});
Static
Adding static methods to a Model is simple as well
Adding static methods to a Model is simple as well
var modelSchema = new Schema({name: String, type: String });
modelSchema.statics.findByName = function(name, attr) {
// this.find({ name: new RegExp(name, 'xx') }, attr);
}
Index
Use index option
var test = new Schema({
name: String,
type: String,
tags : { type: [String], index: true} // Array + index ??
});
// You can also add index method
test.index({ name: 1, type: -1}); // name is true
Schema options
- autoIndex
- capped
- collection
- id
- _id
- read
- safe
- shardKey
Auto Increment
To realize this, we need plugin
mongoose-auto-increment
