In a normal cursor pagination, I would filter and sort the documents based on created
field, which is pretty simple. like this:
// `cursor` is a string const books = await this.BooksModel.find({ ...(cursor ? { created: { $lt: new Date(cursor) } } : null), }) .sort({ created: -1 }) .limit(first)
Meanwhile when implementing search, I (think I) have to sort the results based on textScore
metadata, which could have a duplication. To prevent this I need another field to filter, which is _id
. I imagine it would be something like this:
// `cursor` is { id: string, score: number } const books = await this.BooksModel.aggregate( [ { $match: { _id: { $ne: ObjectId(cursor.id) }, $text: { $search: 'sed' } } }, { $project: { title: 1, score: { $meta: 'textScore' } } }, { $match: { score: { $lt: cursor.score } } } ] )
To achieve the example above, I need the cursor to contain not only the document _id
(like a normal pagination) but also the score
. I imagine the length of the cursor (decoded) would be very long compared to the normal one. Moreover, the cursor now contains an object instead of just string, which is pretty weird to a noob like me. Is this really the way to build cursor-based search pagination?
没有评论:
发表评论