分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

egg-mongoose --- nodejs

发布时间:2023-09-06 02:25责任编辑:白小东关键词:jsnodejs

项目

egg + mongoose


项目结构

配置


egg 安装模块

npm i egg-mongoose --save

config/pulgin.js

exports.mongoose = { ?enable: true, ?package: ‘egg-mongoose‘,};

config/config.default.js

exports.mongoose = { ???url: ‘mongodb://127.0.0.1/demo‘, ???//链接到本地的MongoDB,demo是我本地数据库的名字,根据自己数据库名字进行填写即可 ???options: {},};

数据建模


model/user.js

// app/model/user.jsmodule.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, ‘userInfo‘); ???// model(参数1,参数2,参数3)参数3是你数据表中需要操作的表的名字, ???// 比如我现在要操作的是名字叫mongoTest里面的叫userInfo的表}

service


 service/user.js

‘use strict‘;// app/service/user.jsconst Service = require(‘egg‘).Service;class UserService extends Service { ?async findUserList() { ???return this.ctx.model.User.find() ?}}module.exports = UserService;

controller


 controller/user.js

‘use strict‘;const Controller = require(‘egg‘).Controller;class UserController extends Controller { ?async findUser() { ???// console.log(this.ctx.service.user.findUserList()) ???// let ret = await this.ctx.service.user.findUserList() ???// this.ctx.body = ret ???this.ctx.body = await this.ctx.service.user.findUserList() ?}}module.exports = UserController;

router.js


‘use strict‘;/** * @param {Egg.Application} app - egg application */module.exports = app => { ?const { router, controller } = app; ?router.get(‘/findUser‘, controller.user.findUser);};

查询结果


 

egg-mongoose --- nodejs

原文地址:https://www.cnblogs.com/zyulike/p/10095568.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved