我有一个使用rethinkdb数据库适配器的一些Feathersjs服务开发的Angular 4应用程序。
我不是SQL持久性的新手。在Sql中,我会使用select distinct ... from ...来从车队获得“不同”的汽车制造商,以允许用户过滤此列表或分组。
我怎样才能在羽毛中获得这个?
我在featherjs中使用rethinkdb数据库适配器的自定义钩子解决了我的问题:
module.exports = function (options = {}) {
return function distinct(hook) {
let query = hook.params.query;
// Must be a before hook
if (hook.type !== 'before') {
throw new Error('El hook \'distinct\' sólo puede usarse como hook \'before\' (hooks.distinct).');
}
// Throw error when no field is provided - eg. just users?$distinct
if (query.$distinct === '') {
throw new Error('$distinct no encontrado: ¿Qué campo debería ser distinto? (hooks.distinct)');
}
let distinctValue = query.$distinct || null;
console.log('distinctValue', distinctValue);
if (distinctValue == null) return hook;
// Remove $distinct param from query (preventing errors)
delete query.$distinct;
// Add only the field we are searching for
query = Object.assign({ $select: distinctValue },query)
const rethinkdbQuery = this.createQuery(query);
const r = this.options.r;
// In our case, disable pagination
hook.params.paginate = false;
// Update the query with an additional `distinct` condition
hook.params.rethinkdb = rethinkdbQuery.distinct();
return hook;
}
};