聊聊unicloud的JQL在客户端、云端函数、云端对象中的使用
JQL
,是一种js方式操作数据库的规范,方便与多表联查,它避免了使用db.command进行复杂操作,下面举两个个例子:
//db.command 使用
const dbCmd = db.command
db.collection('goods').where({category: 'computer',memory: dbCmd.gt(8), // 表示大于 8})//JQL使用
db.collection('goods').where(`category == 'computer' && memory > 8`)
//command 使用
const db = uniCloud.database();
exports.main = async (event, context) => {//field => 只返回age字段、_id字段,其他字段不返回const collection = await db.collection('users').field({ 'name': true }).get()return collection
};//JQL使用
exports.main = async (event, context) => {const collection = await db.collection('users').field('name,_id').get()return collection
};
客服端使用JQL语法:
JQL
提供了更简单的联表查询方案,只需在db schema中,将两个表的关联字段建立映射关系,就可以把2个表当做一个虚拟联表来直接查询
const db = uniCloud.database()
// 临时表field方法内需要包含关联字段,否则无法建立关联关系
const order = db.collection('order').field('book_id,quantity').getTemp()
// 临时表field方法内需要包含关联字段,否则无法建立关联关系
const book = db.collection('book').field('_id,title,author').getTemp()
// 注意collection方法内需要传入所有用到的表名,用逗号分隔,主表需要放在第一位
db.collection(order, book).where('book_id.title == "三国演义"') // 查询order表内书名为“三国演义”的订单.get().then(res => {console.log(res);}).catch(err => {console.error(err)})
云函数中使用JQL语法:
exports.main = async (event, context) => {// 获取JQL database引用,此处需要传入云函数的event和context,必传const dbJQL = uniCloud.databaseForJQL({ event,context })// 直接执行数据库操作const bookQueryRes = await dbJQL.collection('book').where("name=='三国演义'").get() return {bookQueryRes}
};
云对象中使用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}}
}
setUser指定用户身份
如需在云函数/云对象中指定执行其他用户身份,需使用setUser
方法
// 指定后续执行操作的用户信息,此虚拟用户将同时拥有传入的uid、role、permission
dbJQL.setUser({uid: 'user-id', // 用户id// 指定当前执行用户的角色为admin。如果只希望指定为admin身份,可以删除uid和permission字段role: ['admin'],permission: [] // 用户权限
})