问题及解决过程
(内含解决过程记录,不想看可以直接跳到解决方法)
今天突然发现一个问题:jql语法直接在云对象中使用是不行的,报错内容如下:
te: code: 100104, error: cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel
官方文档、百度、ChatGPT、都没找到正确解法,之后在CSDN(本站)找到一篇文章,给出了一段在云对象中写JQL的写法,如下:
module.exports = {
// 通用预处理器
_before: function() {
const dbJQL = uniCloud.databaseForJQL({
clientInfo: this.getClientInfo()
})
},
async get() {
// 直接执行数据库操作
const bookQueryRes = await dbJQL.collection('book').where("name=='三国演义'").get()
return {
bookQueryRes
}
}
}
尝试这个写法后,会报 “ te: dbJQL is not defined ” 错误,应该是在预定处理中定义无法被访问到。
解决方法
尝试将 dbJQL 写在方法中,运行成功无报错。
module.exports = {
// 通用预处理器
_before: function() {
},
async get() {
const dbJQL = uniCloud.databaseForJQL({
clientInfo: this.getClientInfo()
})
// 直接执行数据库操作
const bookQueryRes = await dbJQL.collection('book').where("name=='三国演义'").get()
return {
bookQueryRes
}
}
}
或者可以写成
const dbJQL = uniCloud.databaseForJQL({
clientInfo: uniCloud.databaseForJQL().getClientInfo()
})
module.exports = {
// 通用预处理器
_before: function() {
},
async get() {
// 直接执行数据库操作
const bookQueryRes = await dbJQL.collection('book').where("name=='三国演义'").get()
return {
bookQueryRes
}
}
}
暂时只找到这种写法,有更好的写法或解决办法,欢迎留言。