mongoose的增删改查
文章目录
- 一、mongoose是什么?
- 二、使用步骤
- 1.下载
- 2.引入库
- 3.数据库监听
- 4.创建数据类型
- 5.添加
- 6.删除
- 7.更新
- 8.查找
一、mongoose是什么?
mongoose 是一个操作 mongodb 的nodejs 驱动库。
mongodb 是数据库,nodejs 是js的一个运行环境,凭什么nodejs 可以操作 mongodb,所以这个时候就需要相应的驱动程序来提供接口。
二、使用步骤
1.下载
初始化项目 npm init -y
下载 npm i mongoose —save
2.引入库
代码如下:
const mongoose = require('mongoose')
3.数据库监听
代码如下:
// 连接数据库
mongoose.connect('mongodb://127.0.0.1')
// 监听是否连接
mongoose.connection.once('open',function(){
console.log('mongo is running')
})
// 监听是否错误
mongoose.connection.once('err',function(){
console.log('database is not found')
})
// 监听是否断开
mongoose.connection.on('close',function(){
console.log('database is close')
})
4.创建数据类型
创建Schems对象:数据结构和数据类型
// 创建Schems对象:数据结构和数据类型
var Schema = mongoose.mongoose.Schema;
// 创建数据结构和类型
var blogSchema = new Schema({
name:String,
sex:String,
age:Number
})
创建集合Model对象:相当于MongoDB数据库中的集合collection
var orderlist = mongoose.mongoose.model('name',blogSchema)
5.添加
添加单条数据 orderlist({具体数据}).save().then()
orderlist({
name:'lili',
sex:'girl',
age:21
}).save()
.then((res)=>{
console.log('ok')
}),(err)=>{
console.log('err')
}
添加多条数据 orderlist.insertMany([{数据])).then()
orderlist.insertMany([
{
name:'lilei',
sex:'boy',
age:22
},
{
name:'Max',
sex:'girl',
age:22
}
]).then((res)=>{
console.log('添加成功')
}).catch((err)=>{
console.log('失败了')
})
6.删除
清空当前集合所有数据 remove
orderlist.remove().then((res)=>{
console.log('删除成功')
})
删除满足条件的一条数据 deleteOne
orderlist.deleteOne({ name:'lili'}).then((res)=>{
console.log('删除成功')
})
删除满足条件的多条数据 deleteMany
orderlist.deleteMany({ sex:'boy'}).then((res)=>{
console.log('删除成功')
})
7.更新
更新一条数据 update
orderlist.update({ name:'Max'},{ age:23}).then((res)=>{
console.log('update')
})
更新满足条件的多条数据 updateMany
orderlist.updateMany({ name:'Max'},{ age:23}).then((res)=>{
console.log('update')
})
8.查找
查找到当前集合所有数据 orderlist.find().then()
orderlist.find().then((res)=>{
console.log(res)
}).catch((err)=>{
console.log('err')
})
带参数:满足条件的
orderlist.find({ name:'lili'}).then((res)=>{
console.log(res)
}).catch((err)=>{
console.log('err')
})
查找区间
orderlist.find({ price:{ $gt:100,$lt:400}}).then((res)=>{
console.log(res)
})
还没有评论,来说两句吧...