Skip to content

Commit b6c262a

Browse files
mongoose plugin aggregate and search support
1 parent fa7d2c8 commit b6c262a

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

spec/mongoosePluginSpec.js

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,18 @@ let Author = mongoose.model('Author', AuthorSchema);
1515
let PostSchema = new mongoose.Schema({
1616
title: String,
1717
date: Date,
18-
body : String,
18+
body : {
19+
type: String,
20+
text: true,
21+
},
1922
author: {
2023
type: mongoose.Schema.ObjectId,
2124
ref: 'Author'
2225
}
2326
});
2427

28+
PostSchema.index({body: 'text'});
29+
2530
PostSchema.plugin(mongooseCursorPaginate);
2631

2732
let Post = mongoose.model('Post', PostSchema);
@@ -67,4 +72,37 @@ describe('mongoose plugin', (it) => {
6772
t.is(data.hasOwnProperty('next'), true);
6873
t.is(data.hasOwnProperty('hasNext'), true);
6974
});
75+
76+
it('return find results', async function(t) {
77+
let data = await Post.paginate({
78+
query: {title: 'Post #99'},
79+
});
80+
t.is(data.results.length, 1);
81+
});
82+
83+
it('return aggregate results', async function(t) {
84+
let data = await Author.paginateFN({
85+
aggregation: [
86+
{
87+
$lookup: {
88+
from: 'posts',
89+
localField: '_id',
90+
foreignField: 'author',
91+
as: 'posts',
92+
}
93+
},
94+
],
95+
});
96+
t.is(data.results.length, 1);
97+
t.is(Array.isArray(data.results[0].posts), true);
98+
t.is(data.results[0].posts.length, 100);
99+
});
100+
101+
it('return search results', async function(t) {
102+
let data = await Post.paginate({
103+
search: '99',
104+
});
105+
t.is(data.results.length, 1);
106+
});
107+
70108
});

src/mongoose.plugin.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11

22
const find = require('./find');
3+
const search = require('./search');
4+
const aggregate = require('./aggregate');
35
const _ = require('underscore');
46

57
/**
@@ -22,7 +24,9 @@ module.exports = function (schema, options) {
2224
}
2325

2426
param = _.extend({}, param);
25-
27+
28+
if (param.aggregation) return aggregate(this.collection, param);
29+
if (param.search) return search(this.collection, param.search, param);
2630
return find(this.collection, param);
2731
};
2832

0 commit comments

Comments
 (0)