在实际运用中,对于数据库的操做咱们不可能一直在cmd命令行中进行操做,通常状况下须要在node环境中来操做mongodb数据库,这时就须要引入mongoose模块来对数据库进行增删改查等操做。node
首先,启动数据库服务:mongodb
mongod --dbpath (db文件夹路径)
数据库
而后安装mongoose模块:npm
npm install mongoose -Spromise
app.js文件:app
1 const mongoose = require('mongoose') 2
3 // 链接数据库:若是不存在指定数据库文件则会自动建立(该方法会返回一个promise对象)
4 mongoose.connect('mongodb://localhost:27017/project',{ 5 useNewUrlParser:true, 6 useUnifiedTopology:true
7 }).then( async ()=>{ 8 console.log('数据库链接成功'); 9 }.catch(()=>{ 10 console.log('数据库链接失败'); 11 })
创建模型:(代码均在.then回调函数中执行)async
1 // 先定义数据库中集合的数据格式
2 let studentSchema = new mongoose.Schema({ // 表示数据库中集合的数据有 name sex age
3 name:{type:String,require:true}, 4 sex:{type: String}, 5 age:{type: Number,require: true}, // require属性决定该类型数据是否必须存在集合中,为true则必须存在
6 className:{type: String,default:'中二班'} //default属性设置默认值
7 }) 8 let Student = mongoose.model("class1",studentSchema) 9
10 // 简写
11 let Student = mongoose.model('class1',new mongoose.Schema({ 12 name:String, 13 sex:String, 14 age:Number 15 }))
添加数据mongoose
1 //向集合中插入一条数据 create函数返回的是一个 promise 2 let result1 = await Student.create({ 3 name:'张三', 4 sex:'男', 5 age:20 6 }) 7 console.log(result1); 8 9 //向集合中插入多条数据 10 Student.create([ 11 { 12 name:'小海', 13 sex:'男', 14 age:21 15 }, 16 { 17 name:'小菲', 18 sex:'女', 19 age:20 20 }, 21 { 22 name:'小明', 23 sex:'男', 24 age:23 25 } 26 ])
查询数据函数
1 //查询集合中的数据 find函数返回的是一个 promise 2 let result2 = await Student.find({name:'张三'}) 3 console.log(result2);
删除数据ui
1 //删除集合中的一条数据 deleteOne函数返回的也是一个promise 2 let result3 = await Student.deleteOne({name:'张三'}) 3 console.log(result3); 4 5 //删除集合中的多条数据 deleteMany函数返回一个promise 6 let result4 = await Student.deleteMany({name:"张三"}) 7 console.log(result4);
修改数据
1 //更新一条集合中的数据 updateOne函数返回一个promise 2 let result5 = await Student.updateOne({name:'小菲'},{$set:{name:'小红'}},) 3 console.log(result5); 4 5 //更新多条集合中的数据 updateMany函数返回一个promise 6 let result6 = await Student.updateMany({name:"小菲"},{$set:{name:'菲菲'}}) 7 console.log(result6);