微信云数据库使用的是非关系型数据库,类似于Elasticsearch、MongoDB等,与传统的Oracle、MySQL等关系型数据库不同。
建议开发小程序之前先了解一下非关系型数据库基础知识。
绑定insert事件
insert事件里调用db.collection().add()方法,
其中collection里填入集合名称;
data是需要添加的一条记录;
有两种回调方式:
insert: function () {
db.collection('user').add({
data:{
name:'Jerry',
age: 20
},
success: res => {
console.log(res);
},
fail: res => {
console.log(err)
}
})
},
注:本文的增删改查都可以使用这种方式回调,下文不再分为这两类。
insert: function(){
db.collection('user').add({
data: {
name: 'Jack',
age: 20
}
}).then(res=>{
console.log(res);
}).catch(res=>{
console.log(err)
})
},
数据库里产生了一条记录,其中_id是主键,可以利用主键进行修改、删除、查询的操作
绑定delete事件
delete事件调用db.collection().doc().remove()方法
其中collection中填入集合名称;
doc中填入需要修改文档的_id;
delete: function(){
db.collection('user').doc('3e1ef27b5d1da216009d74690092dbe4')
.remove()
.then(res => {
console.log(res);
}).catch(res => {
console.log(res);
})
},
可以从云数据库中对应的那一条记录有没有被删除
绑定update事件
update事件调用db.collection().doc().update()方法;
(注意:有两种方法:update和set,其中update是局部更新,set是全局更新)
其中collection中填入集合名称;
doc中填入需要修改文档的_id;
data里填入修改的字段与字段对应的值
update:function(){
db.collection('user').doc('3e1ef27b5d1da216009d74690092dbe4').update({
data:{
age:100
}
}).then(res=>{
console.log(res);
}).catch(res=>{
console.log(res);
})
},
可以从云数据库中对应的那一条记录有没有被修改
绑定search事件
search事件调用db.collection().where().get()方法
其中collection中填入集合名称;
where中填入需要查找的字段以及对应的值;
search: function(){
db.collection('user').where({
name:'Jerry'
}).get().then(res=>{
console.log(res);
}).catch(res=>{
console.log(res);
})
},
db.collection('****').where({
_openid: '****' // 填入当前用户 openid
}).count().then(res => {
console.log(res.total)
})
更多内容,请关注公众号:程序员高手之路
在公众号回复:小程序资源 即可免费获取以下微信小程序视频教程!