Code Monkey home page Code Monkey logo

egg-mongo-native's Introduction

NPM version NPM quality build status Test coverage David deps Known Vulnerabilities npm download

中文版

Users who don't use Egg.js could use easy-mongodb.

This plugin base on node-mongodb-native, provides the official MongoDB native driver and APIs.

It wraps some frequently-used API to make it easy to use but keep all properties as it is. For example, to find a document you need this with official API

db.collection('name')
  .find(query, options)
  .skip(skip)
  .limit(limit)
  .project(project)
  .sort(sort)
  .toArray();

and with this plugin

app.mongo.find('name', { query, skip, limit, project, sort, options });

Install

$ npm i egg-mongo-native --save

Enable Plugin

// {app_root}/config/plugin.js
exports.mongo = {
  enable: true,
  package: 'egg-mongo-native',
};

Configuration

Single Instance

// {app_root}/config/config.default.js
exports.mongo = {
  client: {
    host: 'host',
    port: 'port',
    name: 'test',
    user: 'user',
    password: 'password',
    options: {},
  },
};

Replica Set (v2.1.0 or higher)

// mongodb://host1:port1,host2:port2/name?replicaSet=test
exports.mongo = {
  client: {
    host: 'host1,host2',
    port: 'port1,port2',
    name: 'name',
    options: {
      replicaSet: 'test',
    },
  },
};

// mongodb://host:port1,host:port2/name?replicaSet=test
exports.mongo = {
  client: {
    host: 'host', // or ['host']
    port: 'port1,port2', // or ['port1', 'port2']
    name: 'name',
    options: {
      replicaSet: 'test',
    },
  },
};

Multiple Instances

Can not set client and clients both.

// {app_root}/config/config.default.js
exports.mongo = {
  clients: {
    db1: {
      host: 'host',
      port: 'port',
      name: 'db1',
      user: 'user',
      password: 'password',
      options: {},
    },
    db2: {
      host: 'host',
      port: 'port',
      name: 'db2',
      user: 'user',
      password: 'password',
      options: {},
    },
  },
};

see config/config.default.js for more detail.

Example

The APIs provided by plugin usually need two arguments. The first is commonly the collection name, and the second is an object keeps the arguments of official API. For example, to insert one document using official API

db.collection('name').insertOne(doc, options);

and using plugin API

const args = { doc, options };
app.mongo.insertOne('name', args);

For Multiple Instances

const args = { doc, options };
app.mongo.get('db1').insertOne('name', args);

The args is an object provides the arguments to official API.

Please read easy-mongodb for all APIs(tansaction is now supported) and more examples.

License

MIT

egg-mongo-native's People

Contributors

brickyang avatar chieveit avatar mackjoner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

egg-mongo-native's Issues

如何插入一个ISODate的数据类型

hi

在使用过程中,我想通过.insert()给数据库插入ISODate类型的数据。

.insert(Time: {ISODate("2018-10-01T00:00:00")})

不知有没有人尝试过插入ISODate的数据类型?

[bug] index.d.ts文件不支持多个数据库实例配置

当config.js 配置为

exports.mongo = {
  clients: {
    db1: {
      host: 'host',
      port: 'port',
      name: 'db1',
      user: 'user',
      password: 'password',
      options: {},
    },
    db2: {
      host: 'host',
      port: 'port',
      name: 'db2',
      user: 'user',
      password: 'password',
      options: {},
    },
  },
};

时,app.mongo理应为Map<string, Mongo>,而node_modules中的index.d.ts已经定义为Mongo。导致ts一直无法通过。即使在app的index.d.ts覆盖app.mongo的定义也不生效。

//我app的index.d.ts
declare module 'egg' {
  interface Application {
    mongo: Map<string, MongoDB>;
  }
  interface Context {
    [key: string]: any;
    multipart: () => Promise<any>;
    // mongo部分
    session: ISession|null;
  }
}

是不是在 egg 2.15 中使用需要用其他配置选项

依赖环境如下

package.json

"dependencies": {
    "egg": "^2.15.1",
    "egg-mongo-native": "^3.5.0",
    "egg-scripts": "^2.11.0"
  }

配置选项如下

plugin.js

exports.mongo = {
  enable: true,
  package: 'egg-mongo-native',
};


config.default.js
exports.mongo = {
    client: {
      host: 'localhost',
      port: '27017',
      name: 'example',
    },
  };

无法创建 mongo 数据库连接对象,然后导致 find 方法不是函数。调试时,mongo 数据类型为 object 不是 MongoDB 类型。

请问,问题出在哪里了?

使用app.mongo.aggregate 报错

调用方法:
var args = [{ $match: {} },{$group: {_id: "max", max_value: {$max: "$id"}}}]; const [result] = await app.mongo.aggregate("member", {args});

报错信息:
TypeError: Cannot read property '$out' of undefined
at Collection.aggregate (E:\workspace\projects\demo\egg-example\node_modules_mongodb@3.0.4@mongodb\lib\collection.js:2455:66)
at MongoDB.aggregate (E:\workspace\projects\demo\egg-example\node_modules_egg-mongo-native@3.0.0@egg-mongo-native\lib\mongo.js:530:8)

Error when insertOne new data

Here is my config
exports.mongo = { client: { host: '127.0.0.1', port: '27017', name: 'test', user: 'root', password: 'root', options: {} } };
and I use it like app.mongo.insertOne('name', '123123');

for my mongoDB
I have a database = test
in the test database i have a collection which named test also
image

the error is show when i call app.mongo.insertOne('name', '123123');
2018-09-18 15:15:24,693 ERROR 44536 nodejs.TypeError: Cannot read property '_id' of undefined

Is that clear for my issue

Please update @types/mongodb to v0.3.19

I found a bug that for @types/mongodb v0.3.17 that the Condition type has a required field $where, which doesn't make any sense.

I was trying to do a $pull operation on mongodb, but it asks me to add a $where clause inside the $pull, otherwise the ts will throw error and not compiling the code.

And this bug is fixed in v0.3.19, so please update it :)

plugin config

exports.mongo = {
enable: true,
package: 'egg-mongo',
};

->

exports.mongo = {
enable: true,
package: 'egg-mongo-native',
};

找不到find()方法

按照redeme里安装和配置插件后,找不到find()方法

console.log(app.config.mongo);
输出为空对象
{}

// plugin.js
'use strict';
exports.jwt = {
  enable: true,
  package: 'egg-jwt',
};

exports.mongo = {
  enable: true,
  package: 'egg-mongo-native',
};
//config.default.js
'use strict';

module.exports = appInfo => {
  const config = (exports = {});

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_117580';

  // add your config here
  config.middleware = [];

  return config;
};

exports.jwt = {
  secret: 'WOAIKEKE1314',
};

exports.mongo = {
  client: {
    host: 'localhost',
    port: '27017',
    name: 'fund',
  },
};

报错

 ERROR 16000 [-/127.0.0.1/-/20ms POST /api/add] nodejs.TypeError: app.mongo.find is not a function
    at MongoDBController.add (D:\html\node\app\controller\mongodb.js:20:40)

transactions 事务支持

Mongo 4.X 开始支持 跨collection transactions 事务支持.
egg-mongo-native也支持一下呗。

配置option后连接失败问题

lib/mongo.js
Object.keys(options).forEach(key => (uriOp +=${key}=${options[key]}&)); url += uriOp.slice(0, -1);
处理下才正常使用

3.4 版本变更是否引入了不兼容元素?

由于使用了 ^3.3.0 版本,新版本 release 后 ci 跑测试失败。
配置格式为

  // config.unittest.ts
  config.mongo = {
    client: {
      host: 'xxxxx.com.cn',
      port: '12450',
      name: 'xxxxx',
      user: 'xxxx',
      password: 'pwd',
      options: {},
    },
  };

错误信息为:

MongoError: not authorized on admin to execute command { getParameter: 1, featureCompatibilityVersion: 1 }
      at /node_modules/[email protected]@mongodb-core/lib/connection/pool.js:581:63
      at authenticateStragglers (node_modules/[email protected]@mongodb-core/lib/connection/pool.js:504:16)
      at Connection.messageHandler (node_modules/[email protected]@mongodb-core/lib/connection/pool.js:540:5)
      at emitMessageHandler (node_modules/[email protected]@mongodb-core/lib/connection/connection.js:310:10)
      at Socket.<anonymous> (node_modules/[email protected]@mongodb-core/lib/connection/connection.js:453:17)
      at addChunk (_stream_readable.js:263:12)
      at readableAddChunk (_stream_readable.js:250:11)
      at Socket.Readable.push (_stream_readable.js:208:10)
      at TCP.onread (net.js:607:20)

随后锁定版本为 3.3.0 则恢复正常。
是否新 release 引入了不兼容元素?

count 方法已被弃用

DeprecationWarning: collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead

是否考虑内部替换 count 方法,或者暴露 countDocuments 方法?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.