追梦随想
追梦随想
  • 发布:2023-04-12 01:24
  • 更新:2023-04-12 11:48
  • 阅读:207

【报Bug】 云对象多个方法共享逻辑,函数内无法使用SQL语句

分类:uniCloud

产品分类: uniCloud/App

示例代码:
async function pureAddTodo(title, content) {  
    // ...add todo 逻辑  
const db = uniCloud.database();  
db.collection('goods').field({  
        title: true,  
        thumbnail: true,  
        market_price: true,  
        sell_price: true,  
        remain_stock: true,  
        goods_unit: true,  
        is_real: true  
    }).where({  
        _id: goods_id,  
        is_on_sale: true  
    }).then((res) => {  
        console.log(res)  
    });  
}  

module.exports = {  
    async tryAddTodo() {  
        try {  
            return addTodo(title, content) // 一定会失败。只能调用 pureAddTodo 这样的非导出方法。  
        } catch (e) {  
            return {  
                errCode: 'add-todo-failed'  
            }  
        }  
    },  
    async addTodo(title, content) {  
        return pureAddTodo(title, content)  
    }  
}

操作步骤:

如上

预期结果:

能正常使用sql语句

实际结果:

TypeError: db.collection(...).field(...).where(...).then is not a function

bug描述:

有些业务场景下某些数据查询需要多次调用,所有需要单独剥离封装为一个公共函数调用,根据文档 云对象多个方法共享逻辑 介绍,发现函数内无法使用SQL语句进行查询操作,会提示

TypeError: db.collection(...).field(...).where(...).then is not a function

就算换成JQL语法也是同样报错

2023-04-12 01:24 负责人:DCloud_uniCloud_VK 分享
已邀请:
DCloud_uniCloud_VK

DCloud_uniCloud_VK

你的语法有问题,按如下语法写

let getRes = await db.collection(...).where(...).field(...).get();

友情提示:

  1. 云函数内异步方法必须用 await
  2. 先where再field可以提升数据库查询性能
  • 追梦随想 (作者)

    这个代码不是原来的代码,我只是把文档内的复制过来,加入了SQL查询,如果where和field的顺序不对,报错信息不是这个的

    2023-04-12 11:33

  • 追梦随想 (作者)

    目前的解决方法只能是在导出对象内定义一个方法,然后在需要调用的方法内用await uniCloud.importObject('xxx') 这样调用才可以正常使用

    2023-04-12 11:34

  • DCloud_uniCloud_VK

    回复 追梦随想: 顺序问题只是提醒下可以优化性能,跟报错无关

    2023-04-12 11:37

  • DCloud_uniCloud_VK

    你把你原来的代码发下看看

    2023-04-12 11:38

DCloud_uniCloud_VK

DCloud_uniCloud_VK

如果按照你目前写的报错信息

 db.collection(...).field(...).where(...).then is not a function

那就是语法问题,应该写成这样

let getRes = await db.collection(...).where(...).field(...).get();

注意,他没有.then的方法,后面接的是.get() 同时前面要加await

  • 追梦随想 (作者)

    哦,看到原因了,也测试了一遍,确实是少写了个get(),他奶奶的,半夜脑子不清醒了,因为最开始用的是JQL语法所以报错了,然后就没注意少写了一部分,抱歉

    2023-04-12 11:50

要回复问题请先登录注册