Skip to content

Commit

Permalink
feat: add aggregate() & index.d.ts (#9)
Browse files Browse the repository at this point in the history
* refacor: update deps

* feat: add aggregate

* feat: add index.d.ts

* test: test aggregate
  • Loading branch information
brickyang authored Jan 21, 2018
1 parent 5f99dbb commit f07f09d
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 27 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ distinct();
createIndex();
listCollection();
createCollection();
aggregate(); // v2.2.0 above
```

You can always use `app.mongo.db` to call all official APIs. You can check the
Expand Down
17 changes: 6 additions & 11 deletions README.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
[node-mongodb-native](https://github.com/mongodb/node-mongodb-native),提供了
MongoDB 官方 driver 及 API。

插件对一些常用 API 进行了简单封装以简化使用,同时保留了所有原版属性。例如,使用
原版 API 进行一次查找需要写
插件对一些常用 API 进行了简单封装以简化使用,同时保留了所有原版属性。例如,使用原版 API 进行一次查找需要写

```js
db
Expand Down Expand Up @@ -108,7 +107,7 @@ exports.mongo = {

### 多个数据库实例配置

> **不能 `client``clients` 都设置,否则会报错。**
> **不能 `client``clients` 都 设置,否则会报错。**
```js
// {app_root}/config/config.default.js
Expand All @@ -134,14 +133,11 @@ exports.mongo = {
};
```


请到 [config/config.default.js](config/config.default.js) 查看详细配置项说明。

## 使用示例

本插件提供的 API 只是对原版 API 进行了必要的简化,所有属性名称与原版 API 一致。
所有针对文档操作的 API,通常接受 2 个参数,第一个参数是 collection 名称,第二个
参数是一个对象,属性名即为原版 API 的所有参数。例如,使用原版 API 进行一次插入
本插件提供的 API 只是对原版 API 进行了必要的简化,所有属性名称与原版 API 一致。所有针对文档操作的 API,通常接受 2 个参数,第一个参数是 collection 名称,第二个参数是一个对象,属性名即为原版 API 的所有参数。例如,使用原版 API 进行一次插入

```js
db.collection('name').insertOne(doc, options);
Expand Down Expand Up @@ -180,15 +176,15 @@ distinct();
createIndex();
listCollection();
createCollection();
aggregate(); // v2.2.0 以上
```

当然,在任何时候你也都可以使用 `app.mongo.db` 调用所有 API。你可以在这里查看所有
API:[Node.js MongoDB Driver API](http://mongodb.github.io/node-mongodb-native/2.2/api/)

## 同步与异步

`node-mongodb-native` 所有 API 都支持 Promise,因此你可以自由地以异步或同步方式
使用本插件。
`node-mongodb-native` 所有 API 都支持 Promise,因此你可以自由地以异步或同步方式使用本插件。

### 异步

Expand Down Expand Up @@ -216,8 +212,7 @@ async function create(doc) {
}
```

如果你使用 `app.mongo.db` 调用原版 API,则也可以使用回调函数。插件封装的 API 不
支持回调函数,因为 Promise 和 async/await 更加优雅。
如果你使用 `app.mongo.db` 调用原版 API,则也可以使用回调函数。插件封装的 API 不支持回调函数,因为 Promise 和 async/await 更加优雅。

Node.js 7.6 开始已经原生支持 async/await,不再需要 Babel。

Expand Down
119 changes: 119 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
CollectionInsertOneOptions,
UpdateWriteOpResult,
Collection,
FindOneAndReplaceOption,
Db,
IndexOptions,
InsertOneWriteOpResult,
InsertWriteOpResult,
CollectionInsertManyOptions,
FindAndModifyWriteOpResultObject,
MongoCountPreferences,
ReadPreference,
CollectionOptions,
CollectionCreateOptions,
} from 'mongodb';

declare class MongoDB {
public db: Db;

public connect(url: string): Promise<Db>;

public insertOne(
name: string,
args?: { doc: Object; options?: CollectionInsertOneOptions }
): Promise<InsertOneWriteOpResult>;

public insertMany(
name: string,
args?: { docs: Object[]; options?: CollectionInsertManyOptions }
): Promise<InsertWriteOpResult>;

public findOneAndUpdate(
name: string,
args?: {
filter: Object;
update: Object;
options?: FindOneAndReplaceOption;
}
): Promise<FindAndModifyWriteOpResultObject>;

public findOneAndReplace(
name: string,
args?: {
filter: Object;
replacement: Object;
options?: FindOneAndReplaceOption;
}
): Promise<FindAndModifyWriteOpResultObject>;

public findOneAndDelete(
name: string,
args?: {
filter: Object;
options?: { projection?: Object; sort?: Object; maxTimeMS?: number };
}
): Promise<FindAndModifyWriteOpResultObject>;

public updateMany(
name: string,
args: {
filter: Object;
update: Object;
options?: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean };
}
): Promise<UpdateWriteOpResult>;

public deleteMany(
name: string,
args: { filter: any; options?: CollectionOptions }
): Promise<number>;

public find(
name: string,
args: {
query: any;
skip?: number;
limit?: number;
project?: any;
sort?: { [key: string]: number };
}
): Promise<any[]>;

public count(
name: string,
args: {
query: any;
options?: MongoCountPreferences;
}
): number;

public distinct(
name: string,
args?: {
key?: string;
query?: any;
options?: { readPreference?: ReadPreference | string };
}
): Promise<any[]>;

public createIndex(
name: string,
args: { fieldOrSpec: string | any; options?: IndexOptions }
): Promise<string>;

public listCollections(args?: {
filter?: any;
options?: { batchSize?: number; readPreference?: ReadPreference | string };
}): Promise<string[]>;

public createCollection(args: {
name: string;
options?: CollectionCreateOptions;
}): Promise<Collection>;

public aggregate(name: string, pipeline: Object[]): Promise<any[]>;
}

export default MongoDB;
7 changes: 7 additions & 0 deletions lib/mongo.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,13 @@ class MongoDB extends EventEmitter {
const options = args.options || {};
return this.db.createCollection(name, options);
}

aggregate(name, pipeline) {
return this.db
.collection(name)
.aggregate(pipeline)
.toArray();
}
}

module.exports = MongoDB;
24 changes: 13 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "egg-mongo-native",
"version": "2.1.0",
"version": "2.2.0",
"description": "MongoDB egg.js plugin using native driver.",
"eggPlugin": {
"name": "mongo"
Expand All @@ -14,17 +14,16 @@
"mongo-driver"
],
"dependencies": {
"@types/mongodb": "^2.2.0",
"mongodb": "^2.2.0"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.0.0",
"egg": "^2.0.0",
"egg-bin": "^4.3.6",
"egg": "^2.2.0",
"egg-bin": "^4.3.7",
"egg-ci": "^1.8.0",
"egg-mock": "^3.13.1",
"eslint": "^4.13.0",
"eslint-config-egg": "^5.1.1",
"egg-mock": "^3.14.0",
"eslint": "^4.15.0",
"eslint-config-egg": "^6.0.0",
"supertest": "^3.0.0",
"webstorm-disable-index": "^1.2.0"
},
Expand All @@ -37,10 +36,13 @@
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run pkgfiles --check && npm run lint && npm run cov",
"pkgfiles": "egg-bin pkgfiles",
"autod": "autod"
"pkgfiles": "egg-bin pkgfiles"
},
"files": ["config", "app.js", "lib"],
"files": [
"config",
"app.js",
"lib"
],
"ci": {
"version": "8, 9"
},
Expand Down
33 changes: 28 additions & 5 deletions test/mongo.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
const mm = require('egg-mock');
const mock = require('egg-mock');
const assert = require('assert');
const { ObjectID } = require('mongodb');

Expand All @@ -8,19 +8,19 @@ describe('test/mongo.test.js', () => {
let NAME;
before(async () => {
NAME = 'test';
app = mm.app({
app = mock.app({
baseDir: 'apps/mongo-test',
});
await app.ready();
});

afterEach(async () => {
await app.mongo.deleteMany('test', {});
mm.restore();
await app.mongo.deleteMany(NAME, {});
mock.restore();
});

after(async () => {
await app.mongo.deleteMany('test', {});
await app.mongo.deleteMany(NAME, {});
app.close();
});

Expand Down Expand Up @@ -493,4 +493,27 @@ describe('test/mongo.test.js', () => {
}
});
});

describe('aggregate()', () => {
const docs = [
{ type: 'doc1' },
{ type: 'doc2' },
{ type: 'doc3' },
{ type: 'doc4' },
];
beforeEach(async () => await app.mongo.insertMany(NAME, { docs }));

it('should success', async () => {
const [ result ] = await app.mongo.aggregate(NAME, [
{ $match: {} },
{
$group: {
_id: null,
count: { $sum: 1 },
},
},
]);
assert.equal(result.count, docs.length);
});
});
});

0 comments on commit f07f09d

Please sign in to comment.