Reputation: 423
I'm using typeorm to connect on mongodb, Is typeorm support sort on relevant score return from full text search mongodb? Like described here.
from mongo, i want to make query as:
db.todos.find( {$text: { $search: "coffee" }}, {score: { "$meta": "textScore" }}) .sort({score: { "$meta": "textScore" }}) .limit(20);
How can i query from MongoRepository from typeorm? Thank you.
Upvotes: 7
Views: 2979
Reputation: 21
I've been working a full day to discover how to make this mongo query work the same way on typeorm. Here's the result of this:
On the schema file, you need to put on the field that you configure your index at mongo @Index({ fulltext: true })
like this (in my case I use the field Title):
@Index({ fulltext: true })
@Column()
title: string;
Inside the order option from method find, you add ['score']: { $meta: "textScore" }
, the score its the field that mongo generate when you`re trying to search by index.
If you need, you can add others kind of filters too inside the order.
And the function find will be like this:
const announcements = await this.ormRepository.find({
where: {
$text: { $search: 'search query here' }
},
//@ts-ignore
order: { ['boosted']: 'DESC', ['score']: { $meta: "textScore" } },
select: ['id', 'title', 'images', 'address', 'categories'],
take: 50,
});
I add the //@ts-ignore because I wasnt able to type this field because it doesn
t exist until the search has been done on mongo, so I just ignore, because the order expect the types 1, -1, undefined, 'ASC' and 'DESC', but it's working very well this way, ordering by score.
Upvotes: 2
Reputation: 297
I've tested the following code and it works:
await todoRepository.find({
where: {
$text: { $search: 'search query here' },
},
take: 20
});
P.S. You need to ensure you have a text index on a field in the Todo collection.
I'm not sure if sorting by score
is working properly with TypeORM. I haven't got any success so far.
Upvotes: 1