eggjs+egg-mongoose操作mongodb数据库

使用的数据库是mongodb数据库,mongodb的数据库表创建就不一一介绍了,可自行查询资料如何创建数据库。

使用的数据库可视化工具是mongodb compass

使用的接口工具是postman

这里使用的egg项目脚手架模板是simple版本,详细创建项目流程可在eggjs官网查阅

1、首先安装egg-mongoose

npm i egg-mongoose

2、在config/config.default.js,配置数据库的地址,以及一些请求跨域的配置

config.mongoose = {
    client: {
      url: 'mongodb://localhost:27017/codemodel',
      options: {
        useUnifiedTopology: true,
      },
    }

  };
// EGG 安全配置
  config.security = {
    csrf: {
      enable: false
    }
  };
config.cors = {
    origin: '*',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
    credentials: true
  };

3、在config/plugin.js,配置egg-mongoose

/** @type Egg.EggPlugin */
module.exports = {
  mongoose: {
    enable: true,
    package: 'egg-mongoose'
},
};

4、在config/code.js,配置一些请求返回码

module.exports={
    DEFAULT: {
        DEMO: 100001
    },
}

在config/config.default.js配置

const code = require('./code.js')
config.CODE = code;

5、在app/extend/context.js,编写一些扩展方法

// 在 app/extend/context.js 文件中定义扩展方法
module.exports = {
    success(data) {
      this.body = {
        code: 0,
        message: 'success',
        data,
      };
    },
    error(code, message) {
        this.body = {
          code,
          message,
        };
      },
  };
  

6、创建数据表model

app/model/collectdbs.js

module.exports = app => {
    const mongoose = app.mongoose;
    const Schema = mongoose.Schema;
  
    const CollectSchema = new Schema({
      filePath: { type: String  },
      fileName: { type: String  },
      fileCreateAt: { type: String  },
      fileUrl: { type: String  },
      account: { type: String  },
      collectName: { type: String  },
      fileUpdateAt:{ type: String  },

    });
    
  
    return mongoose.model('Collectdbs', CollectSchema,'collectdbs');
  }

7、编写service

app/service/collectdbs.js

这里使用了lodash,安装lodash

npm i lodash
const { Service } = require('egg')
const _ = require('lodash')
class CodeModelService extends Service {
    //查
    async list() {
        const { ctx } = this;
        return ctx.model.Collectdbs.find()
    }
    //更新
    async update(params) {
        const _params = _(params).omitBy(_.isUndefined).omitBy(_.isNull).value();
        console.log(params)
        return this.ctx.model.Collectdbs.updateOne(
            {
                _id: params._id
            },
            _params
        );
    }
    //删除
    async delete(params) {
        return this.ctx.model.Collectdbs.deleteOne(params);
    }
    //新增
    async create(params) {
        return this.ctx.model.Collectdbs.insertMany(params);
    }
}
module.exports = CodeModelService;

8、编写对应controller

app/controller/collectdbs.js

这里用到了dayjs,安装dayjs

npm i dayjs
const { Controller } = require('egg');
const dayjs = require('dayjs');
class CollectdbsModel extends Controller {
    //查
    async list() {
        const { ctx, service, config } = this;
        try {
            const result = await service.collectdbs.list();
            ctx.success(result);
        } catch (error) {
            ctx.error({
                code: config.CODE.DEFAULT.DEMO,
                message: error
            })
        }
    }
    //更新
    async update(){
        const { ctx, service, config } = this;
        const _id = ctx.request.body?._id;
        const collectName = ctx.request.body?.collectName;
        const updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); 
        const params={
            _id,
            collectName,
            fileUpdateAt:updateTime
        }
        try {
            const result = await service.collectdbs.update(params);
            ctx.success(result);
        } catch (error) {
            ctx.error({
                code: config.CODE.DEFAULT.DEMO,
                message: error
            })
        }
    }
    //删除
    async delete(){
        const { ctx, service, config } = this;

        const _id = ctx.request.body?._id;

        try {
            await service.collectdbs.delete({_id});
            ctx.success({});
        } catch (error) {
            ctx.error({
                code: config.CODE.DEFAULT.DEMO,
                message: error
            });
        }
    }
    //创建
    async create(){
        const { ctx, service, config } = this;
        const {collectName,fileName,account,fileUrl,filePath}=ctx.request.body;
        const updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); 
        const params={
            collectName,fileName,account,fileUrl,filePath,fileCreateAt:updateTime,fileUpdateAt:updateTime
        }
        try {
            const result = await service.collectdbs.create(params);
            ctx.success(result);
        } catch (error) {
            ctx.error({
                code: config.CODE.DEFAULT.DEMO,
                message: error
            });
        }
    }

}
module.exports = CollectdbsModel;

9、编写对应的router.js

app/router.js

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/collectdbs/list', controller.collectdbs.list);
  router.post('/collectdbs/update',controller.collectdbs.update)
  router.post('/collectdbs/delete',controller.collectdbs.delete)
  router.post('/collectdbs/create',controller.collectdbs.create)

};

10、运行项目

npm run dev

11、效果展示

新增数据

查找数据

删除数据

删除_id为65efc1b63ecbf05aacf9378b

更新数据

修改_id为65efcc3746e1b1e601536e00

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js是一个基于Chrome V8 JavaScript引擎的JavaScript运行环境,可用于服务器端编程。Express是一个基于Node.js平台的Web应用开发框架,提供了简单易用的API,可以快速构建Web应用程序。Mongoose是一个优秀的Node.js模块,用于连接MongoDB数据库,并提供了丰富的API来操作MongoDB数据库。 下面是使用Node.js、Express、Mongoose操作MongoDB的基本流程: 1. 安装Node.js、Express和Mongoose 在终端中执行以下命令: ``` npm install node npm install express npm install mongoose ``` 2. 连接MongoDB数据库 在app.js或server.js文件中,使用Mongoose连接MongoDB数据库: ``` var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); ``` 3. 定义数据模型 在models目录下创建一个JavaScript文件,使用Mongoose定义数据模型: ``` var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ name: String, age: Number, email: String }); module.exports = mongoose.model('User', UserSchema); ``` 4. 实现API接口 在routes目录下创建一个JavaScript文件,实现API接口: ``` var express = require('express'); var router = express.Router(); var User = require('../models/user'); router.get('/users', function(req, res, next) { User.find(function(err, users) { if (err) return next(err); res.json(users); }); }); router.post('/users', function(req, res, next) { var user = new User(req.body); user.save(function(err) { if (err) return next(err); res.json(user); }); }); router.get('/users/:id', function(req, res, next) { User.findById(req.params.id, function(err, user) { if (err) return next(err); res.json(user); }); }); router.put('/users/:id', function(req, res, next) { User.findByIdAndUpdate(req.params.id, req.body, function(err, user) { if (err) return next(err); res.json(user); }); }); router.delete('/users/:id', function(req, res, next) { User.findByIdAndRemove(req.params.id, function(err, user) { if (err) return next(err); res.json(user); }); }); module.exports = router; ``` 5. 启动Express应用 在app.js或server.js文件中启动Express应用: ``` var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var userRoute = require('./routes/user'); app.use(bodyParser.json()); app.use('/api', userRoute); app.listen(3000, function() { console.log('Server listening on port 3000'); }); ``` 6. 测试API接口 通过Postman等工具测试API接口。例如: - GET http://localhost:3000/api/users - POST http://localhost:3000/api/users - GET http://localhost:3000/api/users/5f3e7003c3e1c12345678901 - PUT http://localhost:3000/api/users/5f3e7003c3e1c12345678901 - DELETE http://localhost:3000/api/users/5f3e7003c3e1c12345678901 这样就完成了使用Node.js、Express、Mongoose操作MongoDB的基本流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值