一、clientDB操作数据库
1、查找数据
//db.env.uid 当前用户uid,依赖uni-id
//db.env.now 服务器时间戳
//db.env.clientIP 当前客户端IP
// 查询当前用户的数据
const db = uniCloud.database()
let res = await db.collection('table')
.where({
user_id: db.env.uid
})
//如需一次查询多条数据,可使用jql语法
.where(
dbCmd.or({user_id:1},{user_id:2})
)
.get()
//查询列表分页
const db = uniCloud.database()
db.collection('book')
.where('status == "onsale"')
.skip(20) // 跳过前20条
.limit(20) // 获取20条
.get({
getCount:true //如需查询数据总条数
})
// 上述用法对应的分页条件为:每页20条取第2页
//查询并排序
const db = uniCloud.database()
db.collection('order')
.orderBy('quantity asc, create_date desc') // 按照quantity字段升序排序,quantity相同时按照create_date降序排序
.get()
2、插入数据
const db = uniCloud.database();
db.collection("user")
.add({name: '张三'})
.then((res) => {
uni.showToast({
title: '新增成功'
})
})
.catch((err) => {
uni.showToast({
title: '新增失败'
})
})
3、删除数据
//删除单条记录
const db = uniCloud.database();
db.collection("table1").doc("5f79fdb337d16d0001899566").remove()
//删除该表所有数据
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.get()
res.data.map(async(document) => {
return await collection.doc(document.id).remove();
});
//根据条件查询删除内容
const db = uniCloud.database();
db.collection("table1").where("a>2").remove().then((res) => {
uni.showToast({
title: '删除成功'
})
console.log("删除条数: ",res.deleted);
})
4、更新数据
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.where({_id:'doc-id'})
.update({
name: "Hey",
}).then((res) => {
uni.showToast({
title: '更新成功'
})
})
5、树形结构菜单查询(二级分类)
//DB Schema里配置parentKey来表达父子关系,然后查询时声明使用Tree查询,就可以直接查出树形数据
"properties": {
"_id": {
"description": "ID,系统自动生成"
},
"parent_id": {
"bsonType": "string",
"description": "父id",
"parentKey": "_id", // 指定父子关系为:如果数据库记录A的_id和数据库记录B的parent_id相等,则A是B的父级。
},
}
//查询
db.collection("department").get({
getTree: {}
})