在实际运用中,对于数据库的操作我们不可能一直在cmd命令行中进行操作,一般情况下需要在node环境中来操作mongodb数据库,这时就需要引入mongoose模块来对数据库进行增删改查等操作。

首先,启动数据库服务:

  mongod --dbpath (db文件夹路径)

然后安装mongoose模块:

  npm install mongoose -S

app.js文件:

 const mongoose = require('mongoose')

 // 连接数据库:如果不存在指定数据库文件则会自动创建(该方法会返回一个promise对象)
mongoose.connect('mongodb://localhost:27017/project',{
useNewUrlParser:true,
useUnifiedTopology:true
}).then( async ()=>{
console.log('数据库连接成功');
}.catch(()=>{
console.log('数据库连接失败');
})

创建模型:(代码均在.then回调函数中执行)

 // 先定义数据库中集合的数据格式
let studentSchema = new mongoose.Schema({ // 表示数据库中集合的数据有 name sex age
name:{type:String,require:true},
sex:{type: String},
age:{type: Number,require: true}, // require属性决定该类型数据是否必须存在集合中,为true则必须存在
className:{type: String,default:'中二班'} //default属性设置默认值
})
let Student = mongoose.model("class1",studentSchema) // 简写
let Student = mongoose.model('class1',new mongoose.Schema({
name:String,
sex:String,
age:Number
}))

添加数据

 //向集合中插入一条数据 create函数返回的是一个 promise
let result1 = await Student.create({
name:'张三',
sex:'男',
age:20
})
console.log(result1); //向集合中插入多条数据
Student.create([
{
name:'小海',
sex:'男',
age:21
},
{
name:'小菲',
sex:'女',
age:20
},
{
name:'小明',
sex:'男',
age:23
}
])

查询数据

 //查询集合中的数据 find函数返回的是一个 promise
let result2 = await Student.find({name:'张三'})
console.log(result2);

删除数据

 //删除集合中的一条数据 deleteOne函数返回的也是一个promise
let result3 = await Student.deleteOne({name:'张三'})
console.log(result3); //删除集合中的多条数据 deleteMany函数返回一个promise
let result4 = await Student.deleteMany({name:"张三"})
console.log(result4);

修改数据

 //更新一条集合中的数据 updateOne函数返回一个promise
let result5 = await Student.updateOne({name:'小菲'},{$set:{name:'小红'}},)
console.log(result5); //更新多条集合中的数据 updateMany函数返回一个promise
let result6 = await Student.updateMany({name:"小菲"},{$set:{name:'菲菲'}})
console.log(result6);

  

最新文章

  1. HTML5播放暂停音乐
  2. SQLSERVER取当前月第一天和最后一天
  3. AngularJs $location 和 $window
  4. 《Linux内核设计与实现》读书笔记(十九)- 可移植性
  5. 007 The Inheritance In JAVA
  6. L - Subway - POJ 2502
  7. 理解java设计模式之观察者模式
  8. Pick up lines搭讪
  9. [bzoj1497][NOI2006]最大获利_网络流_最小割
  10. codevs 2622 数字序列
  11. 洛谷P4051 字符加密 [JSOI2007] SA
  12. String.format(String format, Object... args)方法详解
  13. java中一些对象(po,vo,dao,pojo)等的解释
  14. Java编写串口程序
  15. ArcGIS案例学习笔记3_1_ArcMap编辑练习
  16. Apache Rewrite规则详解
  17. Spark中的IsNotNull函数怎么用
  18. Winform中使用折叠窗口
  19. CSS 小结笔记之浮动
  20. Scala中List(Map1,Map2,Map3 ....) 转成一个Map

热门文章

  1. LevelListDrawable
  2. kotlin委托属性
  3. linux中read,write和recv,send的区别
  4. 002-jdk-数据结构-工具类Collections、Arrays、System.arraycopy
  5. WebSphere 安装部署,发布web应用
  6. 用VLC读取摄像头产生RTSP流,DSS主动取流转发(一)
  7. [System Design] Design a distributed key value caching system, like Memcached or Redis
  8. 【miscellaneous】使用Google语音识别引擎(Google Speech API)[3月5日修改]
  9. Official Program for CVPR 2015
  10. 【gcd】辗转相除法