小程序后端数据库搭建(微信小程序数据库怎么建立)

一、前提条件:登录开发者工具软件,配置数据库数据集,操作如下:打开云开发控制台添加集合User二、定义函数://增加新纪录到云数据库onAdd:function(){constdb=wx.

一、前提条件:

登录开发者工具软件,配置数据库数据集,操作如下:

  1. 打开云开发控制台
  2. 添加集合User

小程序后端数据库搭建(微信小程序数据库怎么建立)

小程序后端数据库搭建(微信小程序数据库怎么建立)

二、定义函数:

//增加新纪录到云数据库

onAdd: function () {

const db = wx.cloud.database()

db.collection(‘users’).add({

data: {

count: 1

},

success: res => {

// 在返回结果中会包含新创建的记录的 _id

this.setData({

counterId: res._id,

count: 1

})

wx.showToast({

title: ‘新增记录成功’,

})

console.log(‘[数据库] [新增记录] 成功,记录 _id: ‘, res._id)

},

fail: err => {

wx.showToast({

icon: ‘none’,

title: ‘新增记录失败’

})

console.error(‘[数据库] [新增记录] 失败:’, err)

}

})

},

三、查询、更新、删除和新增

①查询

onQuery: function() {

const db = wx.cloud.database()

// 查询当前用户所有的 counters

db.collection(‘users’).where({

_openid: this.data.openid

}).get({

success: res => {

console.log(res);

this.setData({

queryResult: JSON.stringify(res.data, null, 2)

})

console.log(‘[数据库] [查询记录] 成功: ‘, res)

},

fail: err => {

wx.showToast({

icon: ‘none’,

title: ‘查询记录失败’

})

console.error(‘[数据库] [查询记录] 失败:’, err)

}

})

},

②更新

onCounterInc: function() {

const db = wx.cloud.database()

const newCount = this.data.count + 1

db.collection(‘users’).doc(this.data.counterId).update({

data: {

count: newCount

},

success: res => {

console.log(res);

this.setData({

count: newCount

})

},

fail: err => {

icon: ‘none’,

console.error(‘[数据库] [更新记录] 失败:’, err)

}

})

},

onCounterDec: function() {

const db = wx.cloud.database()

const newCount = this.data.count – 1

db.collection(‘users’).doc(this.data.counterId).update({

data: {

count: newCount

},

success: res => {

this.setData({

count: newCount

})

},

fail: err => {

icon: ‘none’,

console.error(‘[数据库] [更新记录] 失败:’, err)

}

})

},

③删除

if (this.data.counterId) {

const db = wx.cloud.database()

db.collection(‘users’).doc(this.data.counterId).remove({

success: res => {

wx.showToast({

title: ‘删除成功’,

})

this.setData({

counterId: ”,

count: null,

})

},

fail: err => {

wx.showToast({

icon: ‘none’,

title: ‘删除失败’,

})

console.error(‘[数据库] [删除记录] 失败:’, err)

}

})

} else {

wx.showToast({

title: ‘无记录可删,请见创建一个记录’,

})

}

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 203304862@qq.com 举报,一经查实,本站将立刻删除。本文链接:https://xz1898.com/n/286668.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-09-20 11:46
下一篇 2023-09-20 11:47

相关推荐

发表回复

登录后才能评论

联系我们

在线咨询: QQ交谈

邮件:97552693@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息