fworkmongo
v1.0.6
Published
mongodb
Downloads
16
Readme
nodejs 封装 mongodb数据库
引入模块
const db = require('fworkMongo')
await db.connect({
connect:{
name:'test',
url:'mongodb://127.0.0.1:27017/'
},
model:{ //数据模型 可以为空 针对添加数据和更新数据
test:{//数据表名 可以为空
key1: 'String',//数据类型 支持All String、Number、Boolean、Array Object
key2: 'String'
}
}
})
1、插入数据
const res = await db.add('test',data)
1.插入单条数据
const data = {
"key1": "test1",
"key2": "test2"
}
添加成功
res = {
"status": 200,
"ids": ["62c433c4b083dab65d6cdc89"]
}
添加失败
res = {
"status": 400,
"msg": "添加失败!"
}
2.插入多条数据
const data = [
{
"key1": "test1",
"key2": "test2"
},
{
"key3": "test3",
"key4": "test4"
}
]
添加成功
res = {
"status": 200,
"ids": [
"62c43637e41ffcb3eb94f711",
"62c43637e41ffcb3eb94f712"
]
}
添加失败
res = {
"status": 400,
"msg": "添加失败!"
}
2、删除数据
const where = {'_id':db.ID('62cd75e6bce3df9417d2714d')}
1.删除单条数据
const res = await db.remove('test',{
where
})
2.删除多条数据
const res = await db.remove('test',{
where,
all:true
})
返回成功
res = {
"status": 200,
"count": 0 //删除数量
}
返回失败
res = {
"status": 400,
"msg": "删除失败!"
}
3、更新数据
const where = {'_id':db.ID('62cd75e6bce3df9417d2714d')} //查找数据源
const set = {'test':'test2'} //更新数据源
1.更新单条数据
const res = await db.update('test',{
set,
where
})
2.更新多条数据
const res = await db.update('test',{
set,
where,
all:true
})
返回成功
res = {
"status": 200,
"count": 0 //更新数量
}
返回失败
res = {
"status": 400,
"msg": "更新失败!"
}
4、根据查询条件获取总条数
const data = {"key1": "test1"}
const res = await db.count('test',data)
返回成功
res = {
"status": 200,
"count": 0 //符合条件总条数
}
返回失败
res = {
"status": 400,
"msg": "获取失败!"
}
5、条件查询数据
1.根据条件where查询数据
const data = {
where:{
"key1": "test1"
},
skip:0,//跳过指定数目的文档
sort:{'_id':1},//1升序 -1降序
limit:20 //限制20个每页
}
const res = await db.find('test',data)
返回成功
res = {
"status": 200,
"count": 1,
"docs": [
{
"_id": "62d00a998f0db7414f0c6285",
"key1": "test1",
"key2": "test2"
}
]
}
返回失败
res = {
status: 400,
msg: '查询失败!'
}
6、聚合查询数据
根据管道查询数据
const data = [
// {
// $lookup: {
// from: 'test', // 关联表名
// localField: '_id', // 查找表的字段
// foreignField: '_id', // 关联表的字段
// as: 'key1' // 定义返回数据的字段
// }
// },
{
$match:{"key1":"test1"}
},
{
$project:{"key1":0}
}
]
const res = await db.agg('test',data)
返回成功
res = {
"status": 200,
"count": 1,
"docs": [
{
"_id": "62d00a998f0db7414f0c6285",
"key1": "test1",
"key2": "test2"
}
]
}
返回失败
res = {
status: 400,
msg: '查询失败!'
}
7、方法doc 根据id删除或者获取数据
1.获取数据
const res = await db.doc('test').get('62d2a65e99d3232cc742c6e0')
返回成功
res = {
"status": 200,
"count": 1,
"docs": [
{
"_id": "62d2bd172b39191df29a4db8",
"key1": "test1",
"key2": "test2"
}
]
}
返回失败
res = {
status: 400,
msg: '获取失败!'
}
2.删除数据
const res = await db.doc('test').remove('62d2a65e99d3232cc742c6e0')
返回成功
res = {
"status": 200,
"count": 1
}
返回失败
res = {
status: 400,
msg: '删除失败!'
}