nodeJS中使用mongoose模块操作mongodb数据库

时间:2023-03-08 16:37:28
nodeJS中使用mongoose模块操作mongodb数据库

在实际运用中,对于数据库的操作我们不可能一直在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);