我想开发一个基于云开发的微信小程序,功能是一个投票系统,界面有投票选项,票数,投票按钮,用户不能重复对一个投票选项,并且只能投一票,投票选项、票数、投票按钮、用户投票次数都存放在云数据库中,请用代码显示出来
时间: 2024-05-28 16:15:18 浏览: 10
很高兴为您服务!以下是您所需要的代码:
// 初始化云开发
wx.cloud.init({
env: 'your-environment-id'
})
const db = wx.cloud.database()
// 创建投票选项集合
const optionsCollection = db.collection('options')
// 创建已投票用户集合
const votedUsersCollection = db.collection('votedUsers')
// 点击投票按钮时触发
async function onVoteOption(optionId) {
// 获取用户信息
const { userInfo } = await wx.getUserInfo()
// 检查用户是否已投过票
const votedUser = await votedUsersCollection.where({
userId: userInfo.openId
}).get()
if (votedUser.data.length > 0) {
wx.showToast({
title: '您已经投过票了',
icon: 'none'
})
return
}
// 开始投票
const option = await optionsCollection.doc(optionId).get()
const newVoteCount = option.data.voteCount + 1
await optionsCollection.doc(optionId).update({
data: {
voteCount: newVoteCount
}
})
// 记录已投票用户
await votedUsersCollection.add({
data: {
userId: userInfo.openId,
optionId
}
})
wx.showToast({
title: '投票成功',
icon: 'success'
})
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)