1.0.12 • Published 5 years ago

egg-mymongoose v1.0.12

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

egg-mymongoose

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

Egg.js 的 mongoose 插件

安装

$ npm i egg-mymongoose --save

开启插件

exports.mymongoose = {
  enable: true,
  package: "egg-mymongoose"
};

单一连接

配置

// recommended
exports.mymongoose = {
  client: {
    url: "mongodb://127.0.0.1/example",
    options: {}
  }
};

使用

// {app_root}/app/mymongoose/model/user.js
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const UserSchema = new Schema({
    userName: { type: String },
    password: { type: String }
  });

  return mongoose.model("User", UserSchema);
};

// {app_root}/app/controller/user.js
exports.index = async function(ctx) {
  ctx.body = await ctx.mongo.Model.User.find({});
};

多连接

配置

// {app_root}/config/config.default.js
exports.mymongoose = {
  clients: {
    // clientId, access the client instance by app.mongooseDB.get('clientId')
    db1: {
      url: "mongodb://127.0.0.1/example1",
      options: {}
    },
    db2: {
      url: "mongodb://127.0.0.1/example2",
      options: {}
    }
  }
};

使用

// {app_root}/app/mymongoose/model/user.js
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const conn = app.mymongoose.get("db1");

  const UserSchema = new Schema({
    userName: { type: String },
    password: { type: String }
  });

  return conn.model("User", UserSchema);
};

// {app_root}/app/mymongoose/model/book.js
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const conn = app.mymongoose.get("db2");

  const BookSchema = new Schema({
    name: { type: String }
  });

  return conn.model("Book", BookSchema);
};

// app/controller/user.js
exports.index = async function(ctx) {
  ctx.body = await ctx.mongo.Model.User.find({}); // get data from db1
};

// app/controller/book.js
exports.index = async function(ctx) {
  ctx.body = await ctx.mongo.Model.Book.find({}); // get data from db2
};

Default config

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

Multi-mongos support

// {app_root}/config/config.default.js
exports.mongoose = {
  client: {
    url: "mongodb://mongosA:27501,mongosB:27501",
    options: {
      mongos: true
    }
  }
};

Questions & Suggestions

Please open an issue here.

License

MIT

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago