先创建一个db.js 用于连接数据库
/**
* Created by Danny on 2015/9/28 16:44.
*/
//引包
var mongoose = require('mongoose');
//创建数据库连接
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/haha');
//监听open事件
db.once('open', function(callback) {
console.log("数据库成功连接");
});
//向外暴露这个db对象
module.exports = db;
*student.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 }
});
//三、创建静态(类)方法 由Student类(模型)来调用
studentSchema.statics.zhaoren = function(name, callback) {
this.model('Student').find({ name: name }, callback);
// this.model('Student')指当前的类,记住就行
};
//创建修改的静态(类)方法
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中创建学生实例,并同步到数据库
法一:
//定义了一个模型,学生模型,“学生类” 集合
var Student = require("./models/Student.js");
//实例化了一个学生类
var xiaoming = new Student({"name":"小明","age":12,"sex":"男"});
//保存这个学生实例到数据库 持久化
xiaoming.save(function(){
console.log("存储成功");
});
法二(推荐):
//定义了一个模型,学生模型,“学生类” 集合
var Student = require("./models/Student.js");
//用类来创建一个对象(工厂)
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("改年龄成功");
});
更多参考:
https://cnodejs.org/topic/51ff720b44e76d216afe34d9