Skip to content

Instantly share code, notes, and snippets.

@jgutix
Created June 5, 2020 14:55
Show Gist options
  • Save jgutix/71cbb8a9f5946ecd57328862154e3c15 to your computer and use it in GitHub Desktop.
Save jgutix/71cbb8a9f5946ecd57328862154e3c15 to your computer and use it in GitHub Desktop.
Mongodb textScore for Loopback 4
import {DefaultCrudRepository} from '@loopback/repository';
import {Reference, ReferenceRelations} from '../models';
import {MongoDsDataSource} from '../datasources';
import {inject} from '@loopback/core';
export class ReferenceRepository extends DefaultCrudRepository<
Reference,
typeof Reference.prototype.id,
ReferenceRelations
> {
dataSource: MongoDsDataSource;
constructor(
@inject('datasources.mongoDs') dataSource: MongoDsDataSource,
) {
super(Reference, dataSource);
this.dataSource = dataSource;
}
/**
* Loopback 4 queries' filter syntax doesn't seem to support textScore in the order nor fields filter,
* so we need to get the instance of mongodb's driver, in order to query directly
* @param text
*/
async textSearch(text) {
return new Promise<any>((resolve, reject) => {
if (!this.dataSource || !this.dataSource.connector) {
return reject('No connection')
}
const mongodb = this.dataSource.connector;
mongodb.collection(Reference.modelName)
.find(
{ $text: { $search: text } },
{ projection: { name: true, score: { $meta: 'textScore' } } }
)
.sort({ score: { $meta: 'textScore' } })
.toArray(function(err, items) {
if (err) {
return reject(err)
}
return resolve(items);
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment