实现效果:当置顶后,需要按着置顶的时长,自动取消置顶。
如图:当置顶时长到了之后自动删除topping字段,以达到自动取消置顶的效果,自己写了一段代码,能够实现自动删除这个字段,但是当所有数据中都没有topping这个字段后就会报错。哪位大师提供一个更好的实现案例学习下
代码:
// 取消置顶
async timer(){
await app.loadUserInfo();
let openid = await app.globalData.userInfo._openid;
const toppings = await db.collection("wehicle").where({
_openid: openid
}).get()
if(toppings){
const wehicles = toppings.data;
console.log(wehicles);
wehicles.forEach((wehicle, index) => {
const id = wehicle._id;
console.log(id);
if(wehicle.topping.timelength){
setTimeout(function(){
db.collection("wehicle").doc(id).update({
data:{
"topping":_.remove()
}
})
},wehicle.topping.timelength*1000*60)
}
})
}
},
为啥要那么复杂,只需要判断topping是否超过一定时间或者是否为空就行了呀
const that = this;
const code = that.data.code;
const timelength = new Date() + code*1000*60*60;
console.log(timelength);
const index = that.data.index;
const wehicle = that.data.wehicles[index];
const wehicles = that.data.wehicles;
console.log(wehicle)
wx.showLoading({
title: ”正在置顶中...”;
})
wx.cloud.callFunction({
name: "topping",
data: {
id: wehicle._id,
timelength: timelength,
},
success: res => {
console.log(res);
if(!wehicle.topping){
wehicle.topping = (timelength)
}else{
wehicle.topping.push(timelength)
}
wehicle.istoppinged = true;
wehicles[index] = wehicle;
if (wehicle.topping) {
wx.hideLoading();
wx.showToast({
title: ”恭喜!置顶成功!”;,
})
setTimeout(function () {
that.setData({
show_input: false,
wehicles:wehicles
})
}, 800)
} else {
wx.showToast({
title:”置顶失败,请重新置顶!”,
})
}
}
})
},
不删字段,字段有默认值,根据值去处理是否置顶