1.安装monogoose
npm install mongoose -D
2.导入monogoose模块
var mongoose = require (' mongoose ');
3.连接数据库
mongoose.connect(' mongodb://主机名/数据库名称 ',( error ){ if( error ) throw error console.log(' database connect success ')})
4.储存数据步骤
1.定一个Schema骨架
var schema = mongoose.Schema();var studentsSchema = new schema({ name:String, age:Number, set:String})
2.创建骨架模型
var studentsModel = mongoose.model(' students ',studentsSchema); //students --集合名称
3.创建实例
var studentsInstance = new studentsModel();
接下来就是数据库的增删该查
增
studentsInstance.name = 'mogoose';studentsInstance.age = 18;studentsInstance.set = 'men';studentsInstance.save(( error )=>{ if( error ) throw error console.log(' data save success ')})
删
studentsModel.find({ age:18 },( error,result )=>{ if( !error ){ let id = result[0]._id; studentsModel.findByID(id,( error,docs ){ //docs -- 文档 if( !error ){ docs.remove(()=>{ console.log('delete data success') }) } else{ throw error } }) } else{ throw error }})
改
stuentsModel.find({name:'mogoose'},( error,res ){ if( !error ){ let id = res[0]._id; studentsModel.findByID( id,(error,docs){ docs.name = adminMongo; docs.save(( error )=>{ if( !error ){ console.log(' data updata success ') } else{ throw error } }) }) } else{ throw error }})
查
studentsModel.find({set:'men'},( error,data ){ if( !error ){ console.log(data); console.log(' data find success ') } else{ throw error }})