egg-mymongoose
v1.0.12
Published
egg.js mongoose插件
Downloads
4
Readme
egg-mymongoose
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.