db.js
/** * Created by Danny on 2015/9/28 16:44. *///引包var mongoose = require('mongoose');//创建数据库连接,每一个用户都会创建一个db,var db = mongoose.createConnection('mongodb://127.0.0.1:27017/haha');//监听open事件db.once('open', function (callback) { console.log("数据库成功连接");});//向外暴露这个db对象module.exports = db;
students.js
/** * Created by Danny on 2015/9/28 16:47. */var mongoose = require('mongoose');var db = require("./db.js");//创建了一个schema结构。var studentSchema = new mongoose.Schema({ name : {type : String}, age : {type : Number}, sex : {type : String}});//创建静态查找方法studentSchema.statics.zhaoren = function(name, callback) { this.model('Student').find({name: name}, callback);};//创建修改的静态方法studentSchema.statics.xiugai = function(conditions,update,options,callback){ this.model("Student").update(conditions, update, options, callback);}//创建了一个模型,就是学生模型,就是学生类。//类是基于schema创建的。var studentModel = db.model('Student', studentSchema);//向外暴露module.exports = studentModel;
app.js
/** * Created by Danny on 2015/9/28 16:45. *///定义了一个模型,学生模型,“学生类”var Student = require("./models/Student.js");////实例化了一个学生类//var xiaoming = new Student({"name":"小明","age":12,"sex":"男"});////保存这个学生类//xiaoming.save(function(){ // console.log("存储成功");//});//用类来创建一个对象(工厂)Student.create({"name":"小红","age":13,"sex":"女"},function(error){ console.log("保存成功");})//Student.zhaoren("小明",function(err,result){ console.log(result);});Student.xiugai({ "name":"小明"},{$set : {"age":30}},{},function(){ console.log("改年龄成功");});