84550694 2019-06-29
egg-init egg-mongoose --type=simple cnpm install cnpm install egg-mongoose --save npm run dev
config/plugin.js
exports.mongoose = { enable: true, package: 'egg-mongoose', };
config/config.default.js
config.mongoose = { client: { url: 'mongodb://eggadmin:[email protected]/eggcms', options: {}, }, };
app/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,'user'); };
router.js
module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); router.get('/addUser', controller.home.addUser); router.get('/updateUser', controller.home.updateUser); router.get('/deleteUser', controller.home.deleteUser); };
service/user.js
'use strict'; const Service = require('egg').Service; class UserService extends Service { async findUser() { const result = await this.ctx.model.User.find(); return result; } async addUser() { const user = new this.ctx.model.User({ username:"aaa", password:"bbbb" }) user.save(); } async updateUser() { const result = await this.ctx.model.User.updateOne({ "_id":"5c00f0ce862e9227acb56d22" },{ password:"cccccccccc" }); return result } async deleteUser(){ const result = await this.ctx.model.User.deleteOne({ "_id":"5c00f0ce862e9227acb56d22" }); return result } } module.exports = UserService;
controller/home.js
'use strict'; const Controller = require('egg').Controller; class HomeController extends Controller { async index() { const res = await this.service.user.findUser(); console.log(res) this.ctx.body = 'hi, egg'; } async addUser(){ await this.service.user.addUser(); this.ctx.body = 'hi, egg'; } async updateUser(){ await this.service.user.updateUser(); this.ctx.body = 'hi, egg'; } async deleteUser(){ await this.service.user.deleteUser(); this.ctx.body = 'hi, egg'; } } module.exports = HomeController;
model/order.js
module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const OrderSchema = new Schema({ order_id:{ type:String, }, uid:Number, trade_no:String, all_price:Number, all_num:Number, }); return mongoose.model('Order', OrderSchema,'order'); };
service/order.js
'use strict'; const Service = require('egg').Service; class OrderService extends Service { async findOrder() { const result = await this.ctx.model.Order.aggregate([ { $lookup:{ from:"order_item", localField:"order_id", foreignField:"order_id", as:"items" } } ]) return result } } module.exports = OrderService;
controller/order.js
'use strict'; const Controller = require('egg').Controller; class OrderController extends Controller { async index() { const res = await this.ctx.service.order.findOrder() this.ctx.body = res; } } module.exports = OrderController;