点击收藏时可以打印出信息,但不能同步到数据库中,
取消收藏时报错
TypeError: Cannot read property 'length' of undefined
var id = ''
const db = wx.cloud.database()
Page({
data: {
list: {},
collect: false,
shoulist:[]
},
onLoad: function (options) {
id = options.id
this.getlist(options.id)
},
//判断用户是否收藏了该条数据
judge(e){
let that=this
if(e){
for(var i=0;i<e.length;i++){
if(e[i].openid==wx.getStorageSync('openid')){
that.setData({
collect:true
})
break
}
}
}
},
//收藏、取消收藏
clickMe() {
var that = this
let nick = wx.getStorageSync('user')
//判断用户有没有登录,游客状态就跳转登录
if (!wx.getStorageSync('openid')) {
wx.showModal({
title: "收藏失败",
content: "请先登录",
success(res) {
if (res.confirm == true) {
wx.switchTab({//跳转到tabber页
url: '/pages/massage/massage',
})
}
}
})
} else {
//如果collect值为false,进行收藏操作
if (this.data.collect == false) {
//获取用户昵称和openID,通过openID识别用户
if (!that.data.list.shoulist) {
//第一个用户创建数组
let shoulist = [{
nick: nick.nickName,
openid: wx.getStorageSync('openid')
}]
//将获取到的用户信息数据的收藏列表中
db.collection("medic").doc(that.data.list._id).update({
data: {
shoulist: shoulist
}
})
.then(res => {
console.log('shoulist', shoulist)
wx.showToast({
title: '已收藏',
})
that.setData({
collect: true,
})
})
}
else {
let new_shoulist = that.data.list.shoulist
new_shoulist.push({
nick: nick.nickName,
openid: wx.getStorageSync('openid')
})
db.collection("medic").doc(that.data.list._id).update({
data: {
shoulist: new_shoulist
}
})
.then(res => {
that.getlist()
})
wx.showToast({
title: '已收藏',
})
that.setData({
collect: true
})
}
}
else {
//查询收藏列表中的进行此操作的openID
let shoulist = that.data.list.shoulist
for (var i = 0; i < shoulist.length; i++) {
//判断,找到此条数据的收藏列表中的openID,然后进行删除操作
if (shoulist[i].openid == wx.getStorageSync('openid')) {
shoulist.splice(i, 1)//从第i条数据开始删除一条数据
//删除之后更新该条数据的收藏列表
db.collection("medic").doc(that.data.list._id).update({
data: {
shoulist: shoulist
}
})
.then(res => {
that.getlist()
wx.showToast({
icon: 'none',
title: '取消收藏',
})
that.setData({
collect: false
})
})
break
}
}
}
}
},
getlist(){
var that=this
db.collection("medic").doc(id).get()
.then(res=>{
that.setData({
list:res.data
})
that.judge(res.data.shoulist)
})
}
})