Skip to content

Commit 050e9a4

Browse files
authored
Merge pull request #12 from mongoosejs/vkarpov15/version
use single `$search` pipeline stage rather than separate `$match`
2 parents f15dfe4 + ae10ab7 commit 050e9a4

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

search/index.js

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ const contentSchema = new mongoose.Schema({
99
title: { type: String, required: true },
1010
body: { type: String, required: true },
1111
url: { type: String, required: true },
12-
version: { type: String }
12+
version: { type: String },
13+
versionNumber: { type: Number }
1314
});
1415

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

2425
const query = req.query.search.toString();
25-
const version = req.query.version;
26+
const version = req.query.version ? +req.query.version.replace(/\.x$/, '') : null;
2627
let results = await Content.aggregate([
2728
{
2829
$search: {
2930
index: 'mongoose-content',
30-
text: {
31-
query,
32-
path: { wildcard: '*' },
33-
fuzzy: {}
31+
compound: {
32+
must: [
33+
...(version ? [{
34+
equals: {
35+
path: 'versionNumber',
36+
value: version
37+
}
38+
}] : []),
39+
{ text: { query, path: { wildcard: '*' }, fuzzy: {} } }
40+
]
3441
}
3542
}
3643
},
37-
{ $match: { version } },
38-
{
39-
$addFields: {
40-
score: {
41-
$meta: 'searchScore'
42-
}
43-
}
44-
},
45-
{ $sort: { score: -1 } },
4644
{ $limit: 10 }
4745
]);
4846

0 commit comments

Comments
 (0)