在云函数中对云数据库进行增删改查
json文档格式的数据库,数据库的格式都是json文档的形式
数据表说的就是集合
使用数据库
首先要获取数据库的引用。使用uniCloud.database这样就能获取数据库的引用。
const db = uniCloud.database();
获取集合的引用
const collection = db.collection()
传一个参数就是集合的名字
const collection = db.collection('user')
添加一条数据,然后输出
const collection = db.collection('user')let res = await collection.add({name: 'uni-app'})console.log('数据插入:')console.log(JSON.stringify(res))
注意事项
这里必须加上await 否则服务器上添加失败。注意注意注意。!!!!
测试运行
批量添加数据


上面用了async。下面用上await,这样才是一个同步的接口
注意多条数据插入,这里必须用大括号,括起来。
const collection = db.collection('user')let res = await collection.add([{name: 'uni-app'},{name: 'html',type: '前端'}])console.log('数据插入:')console.log(JSON.stringify(res))


{"inserted":2,"result":{"0":"624655396764c00001fb739d","1":"624655396764c00001fb739e"},"ids":["624655396764c00001fb739d","624655396764c00001fb739e"]}

删除
.doc找到指定的记录
根据id查找到这条数据
找到记录并删除

const collection = db.collection('user')const res = await collection.doc("624654603e80590001c61160").remove();console.log(res)






