uniCloud传统方式调用数据库-基本操作
1.后台云函数
todo/index.js
'use strict';
// 查询所有
const queryAll =(collection,params)=>{
return collection.get()
}
// 新增
const add = (collection,data)=>{
return collection.add(data)
}
// 删除
const del = (collection,params)=>{
return collection.doc(params.id).remove()
}
// 更新
const update = (collection,params)=>{
return collection.doc(params.id).update({name:params.name})
}
const handlerObj = {
get: queryAll,
post:add,
del,
update
}
exports.main = async (event, context) => {
//event为客户端上传的参数
console.log('event : ', event)
const db = uniCloud.database();
// 获取 `user` 集合的引用
const collection = db.collection('todo');
return handlerObj[event.method](collection,event.params)
};
1. 前端uniapp调用
submit(){
if(!this.formData.name){
return 0;
}
uniCloud.callFunction({
name: 'todo',
data: {method:"post",params:{name:this.formData.name}}
}).then((res) => {
this.queryAll()
}).catch((err) => {
console.error(err)
})
},
del(id){
uniCloud.callFunction({
name: 'todo',
data: {method:"del",params:{id}}
}).then((res) => {
this.queryAll()
}).catch((err) => {
console.error(err)
})
},
update(item){
uniCloud.callFunction({
name: 'todo',
data: {method:"update",params:{id:item._id,name:item.name + '-' }}
}).then((res) => {
this.queryAll()
}).catch((err) => {
console.error(err)
})
},
queryAll(){
uniCloud.callFunction({
name: 'todo',
data: {method:"get",params:{}}
}).then((res) => {
this.todoList = res.result.data || []
}).catch((err) => {
console.error(err)
})
}
浙公网安备 33010602011771号