npm install mongoose -S
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myappdatabase');
Simple Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var customerSchema = new Schema({
name: String,
address: String,
city: String,
state: String,
country: String,
zipCode: Number,
createdOn: Date,
isActive: Boolean
});
var simpleSchema = new Schema({ fieldName: SchemaType });
Complex Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// parent customer schema...
var customerSchema = new Schema({
name: { first: String, last: String },
address: [ addressSchema ],
createdOn: { type: Date, default: Date.now },
isActive: { type: Boolean, default: true}
});
// child address schema...
var addressSchema = new Schema({
type: String,
street: String,
city: String,
state: String,
country: String,
postalCode: Number
});
Alowed Data Type
Mongoose Schema Type
Javascript Data Type
String
String
Number
Number
Boolean
Boolean
Date
Object
Buffer
Object
Mixed
Object
ObjectId
Object
Array
Array(Object)
Adding custom method
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
age: Number
});
userSchema.methods.dudify = function() {
this.name = this.name + '-dude';
return this.name;
};
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
Using custom method
var User = require('./app/models/user');
var user = new User({
name: 'Hemant',
age: 20
});
user.dudify(function(err, name) {
if (err) throw err;
console.log('Your new name is ' + name); // Hemant-dude
});
// call the built-in save method to save to the database
user.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
});
Run a Function Before Saving
Here is the code to add to our Schema to have the date added to created_at if this is the first save, and to updated_at on every save
// on every save, add the date
userSchema.pre('save', function(next) {
// get the current date
var currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});