Skip to content

Commit

Permalink
Merge pull request #12 from mongoosejs/vkarpov15/version
Browse files Browse the repository at this point in the history
use single `$search` pipeline stage rather than separate `$match`
  • Loading branch information
vkarpov15 authored Apr 28, 2023
2 parents f15dfe4 + ae10ab7 commit 050e9a4
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions search/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const contentSchema = new mongoose.Schema({
title: { type: String, required: true },
body: { type: String, required: true },
url: { type: String, required: true },
version: { type: String }
version: { type: String },
versionNumber: { type: Number }
});

module.exports = async function search(context, req) {
Expand All @@ -22,27 +23,24 @@ module.exports = async function search(context, req) {
Content = conn.model('Content', contentSchema, 'Content');

const query = req.query.search.toString();
const version = req.query.version;
const version = req.query.version ? +req.query.version.replace(/\.x$/, '') : null;
let results = await Content.aggregate([
{
$search: {
index: 'mongoose-content',
text: {
query,
path: { wildcard: '*' },
fuzzy: {}
compound: {
must: [
...(version ? [{
equals: {
path: 'versionNumber',
value: version
}
}] : []),
{ text: { query, path: { wildcard: '*' }, fuzzy: {} } }
]
}
}
},
{ $match: { version } },
{
$addFields: {
score: {
$meta: 'searchScore'
}
}
},
{ $sort: { score: -1 } },
{ $limit: 10 }
]);

Expand Down

0 comments on commit 050e9a4

Please sign in to comment.