mongoose操作数据库
1,mongoose模块
mongoose 简介
Mongoose库简而言之就是在node环境中操作MongoDB数据库的一种便捷的封装,一种对象模型工具,Mongoose将数据库中的数据转换为JavaScript对象以供你在应用中使用。
2,mongoose的操作流程
安装mongoose
npm install mongoose -S
引入mongoose
const mongoose = require('mongoose') // mongoose 就是一个实例,这个实例身上有很多的方法
连接数据库
使用mongoose连接数据库的前提条件是:
1、mongo数据库已经运行。
2、已经安装了mongoose包
例如:连接本地mongodb ,本机的ip 127.0.0.1,端口:27017 数据库:students
mongoose.connect("mongodb://127.0.0.1:27017/students",function(err){
if(!err){ //如果连接成功,则打印出connected to Mongodb
console.log("connected to Mongodb");
}else{
throw err;//如果连接失败,则抛出异常
}
});
创建骨架【 定义字段 】
类似: 一个表就是一个骨架,所以骨架不止一个。
var Schema = mongoose.Schema;
const studentSchema = new Schema({
name: String,
age: String
})
创建模型 -> 用于操作数据库
通过模式studentSchema 创建一个模型studentModel
// const studentModel = mongoose.model( 集合名称【 复数 】,对应的骨架 )
const studentModel = mongoose.model("students",studentSchema );
创建实体 -> 新增数据
const data = new studentModel ();
data.name="tangyan";
data.age="18";
//通过save方法保存
data.save((err)=>{
if (err) {
console.log('保存失败');
return;
}
});
删除数据
思路:
1、删除数据首先要知道删除哪一条信息,需要知道信息的id.
2、把对应id的数据查询出来,执行remove方法
假如我们要删除id=”57e24521a755e1154039a403”的数据。
//xxx.findById( _id, ( err,doc ) => { doc.remove() {})
var id=”57e24521a755e1154039a403”;
studentModel.findById(id,(err,doc)=>{
if(!doc){
return next(new NotFound("Doc not found"))
}else{
doc.remove(function(){
console.log('删除成功');
})
}
});
** 修改数据**
思路:
先把对应id的数据查询出来,对需要修改的字段重新赋值,然后执行save方法保存,假如我们要修改id=”57e24521a755e1154039a403”的数据。
// xxx.findById( _id, ( err,doc ) => { doc.name = xxx doc.save() })
var id=”57e24521a755e1154039a403”;
studentModel.findById(id,(err,doc)=>{ console.log(doc);
doc.name="aaa" ; //把name修改为bbb
doc.save((err) =>{
if(!err){
console.log('修改成功');
}else{
throw err;
}
});
});
查找数据
下面find第一个参数{}里面为空,表示查询所有的数据:
docs表示查询的结果集合,可用于渲染ejs模板引擎。
// user.find({},( err,docs ) => { })
studentModel.find({},(err,docs)=>{
console.log(docs);
});