egg-mongoose

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

Egg.js的mongoose插件.

安装

  1. $ npm i egg-mongoose --save

配置

改变 {app_root}/config/plugin.js 来启用 egg-mongoose 插件:

  1. exports.mongoose = {
  2. enable: true,
  3. package: 'egg-mongoose',
  4. };

简单连接

配置

  1. // {app_root}/config/config.default.js
  2. exports.mongoose = {
  3. url: 'mongodb://127.0.0.1/example',
  4. options: {},
  5. };
  6. // recommended
  7. exports.mongoose = {
  8. client: {
  9. url: 'mongodb://127.0.0.1/example',
  10. options: {},
  11. },
  12. };

示例

  1. // {app_root}/app/model/user.js
  2. module.exports = app => {
  3. const mongoose = app.mongoose;
  4. const Schema = mongoose.Schema;
  5. const UserSchema = new Schema({
  6. userName: { type: String },
  7. password: { type: String },
  8. });
  9. return mongoose.model('User', UserSchema);
  10. }
  11. // {app_root}/app/controller/user.js
  12. exports.index = function* (ctx) {
  13. ctx.body = yield ctx.model.User.find({});
  14. }

多连接

配置

  1. // {app_root}/config/config.default.js
  2. exports.mongoose = {
  3. clients: {
  4. // clientId, access the client instance by app.mongooseDB.get('clientId')
  5. db1: {
  6. url: 'mongodb://127.0.0.1/example1',
  7. options: {},
  8. },
  9. db2: {
  10. url: 'mongodb://127.0.0.1/example2',
  11. options: {},
  12. },
  13. },
  14. };

示例

  1. // {app_root}/app/model/user.js
  2. module.exports = app => {
  3. const mongoose = app.mongoose;
  4. const Schema = mongoose.Schema;
  5. const conn = app.mongooseDB.get('db1');
  6. const UserSchema = new Schema({
  7. userName: { type: String },
  8. password: { type: String },
  9. });
  10. return conn.model('User', UserSchema);
  11. }
  12. // {app_root}/app/model/book.js
  13. module.exports = app => {
  14. const mongoose = app.mongoose;
  15. const Schema = mongoose.Schema;
  16. const conn = app.mongooseDB.get('db2');
  17. const BookSchema = new Schema({
  18. name: { type: String },
  19. });
  20. return conn.model('Book', BookSchema);
  21. }
  22. // app/controller/user.js
  23. exports.index = function* (ctx) {
  24. ctx.body = yield ctx.model.User.find({}); // get data from db1
  25. }
  26. // app/controller/book.js
  27. exports.index = function* (ctx) {
  28. ctx.body = yield ctx.model.Book.find({}); // get data from db2
  29. }

默认配置

访问 config/config.default.js查看更多细节.

Mongo集群支持

  1. // {app_root}/config/config.default.js
  2. exports.mongoose = {
  3. client: {
  4. url: 'mongodb://mongosA:27501,mongosB:27501',
  5. options: {
  6. mongos: true,
  7. },
  8. },
  9. };

问题 & 建议

请在这里创建一个issue。

贡献

如果你是一个贡献者,请查看这里CONTRIBUTING

许可证

MIT