node连接mongoDB
使用mongoose连接数据库
-
安装mongoose
npm install mongoose -S
yarn add mongoose
-
引入mongoose
var mongoose = require('mongoose')
-
连接数据库
使用connect连接mongodb数据库,端口号27017
mongoose.connect('mongodb://localhost:27017/H51905',{useNewUrlParser:true})
-
返回待定状态:
connect()返回一个状态待定(pending)的连接,接着我们加上成功提醒和失败警告。
var db = mongoose.connection
-
监听连接状态:
使用mongoose下面的事件监控连接状态 error open连接成功时,回调函数会被调用。
db.on('error', console.error.bind(console, '连接错误'))
db.once('open', function(){console.log('连接成功!')})
-
定义数据模型
(定义数据库字段)
var stuModel = mongoose.Schema({
name: {type:String,required:true},
age: {type:String,required:true},
class:{type:String,required:true},
height:{type:String}
});
-
传递model_创建集合:_
将定义好的模型传到mongoose.model()中.类似创建集合
数据库为student,自动将数据库名变为复数students
const personCol=mongoose.model("student",stuModel)
-
保存数据到数据库
要保存数据,必须new当前模型,会返回一个对象,这个对象可以调用save()
let props={
name:"李磊",
age:'23',
class:'1905'
}
const personObj=new PersonCol(props)
//1_promise函数保存数据
personObj.save().then(res=>{
console.log(res);
})
//在mongoose调用此方法会返回一个待定状态pending
//因为mongoose操作数据库的方法都是基于promise封装的
//2_普通函数保存数据
personObj.save()((err,res)=>{
if(err) throw err
console.log(res);
})
-
查询库
personObj.find().then(res=>{console.log(res)})