题外话:
学习mongodb之后,算是了解了什么是非关系型数据库,然而每个操作时需要一直使用数据库连接的语句,即使封装起来也会很繁琐,因此如果能够选择一种驱动来操作mongodb,那node开发的效率及代码整洁度会更高。
正文:
从资料中了解到,通过java三大框架的思路将js的对象与数据库mongodb产生关系,并持久化。而这也颠覆了自己的数据库操作,因为学习mongoose之后,根本不需要操作数据库,也就是说没有db的写法。(如果自学估计会一脸懵逼几天)
首先,通过http://mongoosejs.com/的官方文档我们可以自己使用hello world。然后就会发现全程都在创建类,实例化类,调用类,但是却是实实在在的出现在了数据库中。这便是用操作对象的方式操作数据库。
接下来,便是mongoose的语法现象。
1.数据库连接
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
2.定义模型
var Cat = mongoose.model('Cat', { name: String });
3.实例化类
var kitty = new Cat({ name: 'Zildjian' });
4.类方法的使用
kitty.save(function(err) {
if (err) {
console.log(err);
}else {
console.log('meow');
}});
var studentSchema = new mongoose.Schema({
name : {type : String},
age : {type : Number},
sex : {type : String}
});
定义Schema的静态方法
1.创建静态方法
studentSchema.statics.find = function(name, callback){
this.model('Student').find({name: name}, callback); //this.model('Student')指的是当前这个类
};
studentSchema.statics.update =function(conditions,update,options,callback){
this.model("Student").update(conditions, update, options,callback);
}
定义Schema的实例方法
1.创建实例方法
studentSchema.methods.find = function(name, callback){
this.model('Student').find({name: name}, callback); //this.model('Student')指的是当前这个类
};
this.model("Student").update(conditions, update, options,callback);
}
定义Schema的静态方法
1.创建静态方法
studentSchema.statics.find = function(name, callback){
this.model('Student').find({name: name}, callback); //this.model('Student')指的是当前这个类
};
studentSchema.statics.update =function(conditions,update,options,callback){
this.model("Student").update(conditions, update, options,callback);
}