微信小程序存储云数据库中查询的结果

    技术2026-08-27  5

    初次接触数据库,查询结果可以打印出来,但不能存到页面变量里。

    getMsg:function(){ //调用云函数获取该openid的热点信息 wx.cloud.callFunction({ name:'getOpenid' }).then(res => { console.log(res.result.openid); //查询该openid下添加的素材 db.collection('mySuCai').where({ _openid: res.result.openid // _openid:'oek_x5GiusqG44pi1mcn9lXFrjao' }) .get({ success: function(res) { // 打印查询到的数据并存储 console.log(res) console.log(res.data) this.setData({ // msg:JSON.parse(res.data).subjects msg:res.data }) } }) }).catch(err => { console.error(err); }); },

    看上去逻辑毫无问题,但appdata里没存进去值,最后找到的原因是在success里,this指针被重用了,所以setData的时候没用。

    解决方法是用that把this存起来

    getMsg:function(){ var that = this //调用云函数获取该openid的热点信息 wx.cloud.callFunction({ name:'getOpenid' }).then(res => { console.log(res.result.openid); //查询该openid下添加的素材 db.collection('mySuCai').where({ _openid: res.result.openid // _openid:'oek_x5GiusqG44pi1mcn9lXFrjao' }) .get({ success: function(res) { // 打印查询到的数据并存储 console.log(res) console.log(res.data) that.setData({ // msg:JSON.parse(res.data).subjects msg:res.data }) } }) }).catch(err => { console.error(err); }); },
    Processed: 0.013, SQL: 9