mongoose是在node.js異步環(huán)境下對mongodb進(jìn)行便捷操作的對象模型工具。本文將詳細(xì)介紹如何使用Mongoose來操作MongoDB
案例要求:
- 首先要掌握nodejs 、mongodb
- 安裝mongodb數(shù)據(jù)庫
- 安裝nodejs環(huán)境
- npm install mongoose 下載mongoose包
案例包含三個(gè)文件:
- db.js --創(chuàng)建數(shù)據(jù)庫連接
- Student.js -- 類骨架模型
- app.js -- 調(diào)用模型
db.js
/**
* Created by prettyRain on 2018/12/24.
* 連接數(shù)據(jù)庫
*/
//引入包
var mongoose = require('mongoose');
//創(chuàng)建數(shù)據(jù)庫連接
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/haha');
db.on('error',console.error.bind(console,'error'));
db.once('open',function(callback){
console.log("數(shù)據(jù)庫連接成功");
});
module.exports = db;
Student.js
/**
* Created by prettyRain on 2018/12/24.
* student骨架
* model : 由Schema構(gòu)造生成的模型,除了Schema定義的數(shù)據(jù)庫骨架以外,
* 還具有數(shù)據(jù)庫操作的行為,類似于管理數(shù)據(jù)庫屬性、行為的類
*/
var mongoose = require('mongoose');
var db = require('./db.js');
/**
* schema :一種以文件形式存儲的數(shù)據(jù)庫模型骨架,無法直接通往數(shù)據(jù)庫端,也就
* 是說它不具備對數(shù)據(jù)庫的操作能力.可以說是數(shù)據(jù)屬性模型(傳統(tǒng)意義的
* 表結(jié)構(gòu)),又或著是“集合”的模型骨架
*/
var Schema = mongoose.Schema;
var studentSchema = new Schema({
name : {type:String},
age : {type:Number},
sex : {type:String}
})
/**
* 自定義類方法
*/
//插入數(shù)據(jù)
studentSchema.statics.add = function(paramJSON,callback){
this.model('Student').create(paramJSON,function(err,result){callback(err,result)});//類方法
}
//查詢數(shù)據(jù)
studentSchema.statics.queryStudent = function(paramJSON,callback){
console.log(this.model);
//this.model('Student'):Student 模型
this.model('Student').find(paramJSON,callback);//類方法
}
//修改數(shù)據(jù)
studentSchema.statics.updateStudentMany = function(whereStr,updateStr,options,callback){
this.model('Student').updateMany(whereStr,updateStr,options,callback);//類方法
}
/**
* 自定義實(shí)例方法
*/
//插入數(shù)據(jù)
studentSchema.methods.add = function(callback){
//this:student實(shí)例對象
this.save(callback);//實(shí)例方法
}
//查詢數(shù)據(jù)
studentSchema.methods.queryStudent = function(callback){
console.log(this.model);
//this.model('Student'):Student 模型
this.model('Student').find({name:this.name},callback);//類方法
}
var student = db.model('Student',studentSchema);
module.exports = student;
app.js
/**
* Created by prettyRain on 2018/12/24.
*/
var Student = require('./models/Student.js');
//實(shí)例化類
/*var tom = new Student({"name":"tom",age:12,sex:"男"});
tom.save(function(err){
console.log('保存成功');
})*/
//
/*Student.create({"name":"anli",age:13,sex:"女"},function(err){
console.log("保存成功");
})*/
/*Student.add({"name":"jkon","age":15,sex:"男"},function(err,result){
console.log(result);
})*/
/*var tom = new Student({"name":"tom",age:12,sex:"男"});
tom.add(function(err){
console.log('保存成功');
})*/
Student.queryStudent({name:"tom"},function(err,result){
console.log(result);
})
var tom = new Student({name:"tom"});
tom.queryStudent(function(err,result){
console.log(result);
})
Student.updateStudentMany({name:"tom"},{$set:{age:15}},{},function(err,result){
console.log(result);
})