使用goctl model 生成MongoDB操作模板

使用goctl model 生成MongoDB操作模板

goctl model 为go-zero下的工具模块中的组件之一,目前支持MongoDB进行model层代码生成。官网有对MySQL的使用方法,但是没有对MongoDB的使用进行讲解,那么我下面介绍goctl model对MongoDB的使用方法。

下面是各个参数的含义,主要用的是 -e -dir -t
-e表示的是生成一个简单的增删改查接口,-dir是生成文档放在的目录
-t是生成文件的前缀名称
-c是带缓存的

Usage:                                                                           
  goctl model mongo [flags]                                                      
                                                                                 
Flags:                                                                           
      --branch string   The branch of the remote repo, it does work with --remote
  -c, --cache           Generate code with cache [optional]                      
  -d, --dir string      The target dir
  -e, --easy            Generate code with auto generated CollectionName for easy declare [optional]
  -h, --help            help for mongo
      --home string     The goctl home path of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
      --remote string   The remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
                        The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
      --style string    The file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
  -t, --type strings    Specified model type name
1、这是我自己生成的命令:goctl model mongo -e -dir ./model/edgeinstance -t edgeinstance 生成了这几个文件:

在这里插入图片描述

2、重点:记得先把EdgeinstanceCollectionName 名字改成自己的MongoDB的表名,这个名字在edgeinstancemodelgen.go文件头部
const EdgeinstanceCollectionName = "edgeinstance"
3、现在就可以进行开发了,但是你会发现他提供的crud根本不够用,所以需要自己定义新的curd。

这时候不能直接在edgeinstancemodelgen.go文件里面定义新的方法,因为这个文件是不能修改的,重新生成会丢失代码。
只能增加多一个文件,我命名为edgeinstancemodeladditional.go,里面就可以写你的方法代码了。
最后记得在edgeinstancemodel.go文件里面的接口中加多你新增的接口

EdgeinstanceModel interface {
		edgeinstanceModel
		edgeInstanceModelAdditional
	}

在这里插入图片描述
这是我的一部分的业务代码

package model

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/mon"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type edgeInstanceModelAdditional interface {
	ExistByName(ctx context.Context, name string) (bool, error)
	ExistById(ctx context.Context, id string) (bool, error)
	ExistByIdAndName(ctx context.Context, id, name string) (bool, error)
	UpdateById(ctx context.Context, ei *Edgeinstance) error
	SearchInstance(ctx context.Context, name string, state bool) ([]Edgeinstance, error)
}

func (m *defaultEdgeinstanceModel) ExistByName(ctx context.Context, name string) (bool, error) {
	
}

func (m *defaultEdgeinstanceModel) ExistById(ctx context.Context, id string) (bool, error) {
	
}

func (m *defaultEdgeinstanceModel) ExistByIdAndName(ctx context.Context, id, name string) (bool, error) {
	
}

func (m *defaultEdgeinstanceModel) UpdateById(ctx context.Context, ei *Edgeinstance) error {
	
}

func (m *defaultEdgeinstanceModel) SearchInstance(ctx context.Context, name string, state bool) ([]Edgeinstance, error) {
	
}
4、初始化MongoDB客户端的方法:
MongoDB: model.NewEdgeinstanceModel(c.Mongo.Url, c.Mongo.Db)

注意url是MongoDB的连接url,格式百度搜索一下。

5、调用自己写的方法
instances, err := l.svcCtx.MongoDB.SearchInstance(l.ctx, in.Name, in.State)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Egg.js 中使用 MongoDB生成表的过程如下: 1. 首先,确保已经在你的项目中安装了 MongoDB 相关的依赖。可以使用 npm 或者 yarn 进行安装,如下所示: ``` npm install egg-mongoose --save ``` 2. 在 Egg.js 的配置文件 (`config/config.default.js` 或者 `config/config.prod.js`) 中进行相关配置。你需要添加以下内容: ```javascript // config/config.default.js exports.mongoose = { client: { url: 'mongodb://localhost:27017/your_database_name', options: {}, }, }; ``` 注意将 `'mongodb://localhost:27017/your_database_name'` 替换为你实际的 MongoDB 连接地址和数据库名称。 3. 创建 Model 文件,在 Egg.js 中,可以使用 Mongoose 来定义模型。在 `app/model` 目录下创建一个新的 JavaScript 文件,例如 `user.js`,并编写以下代码: ```javascript // app/model/user.js module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const UserSchema = new Schema({ name: { type: String }, age: { type: Number }, email: { type: String }, }); return mongoose.model('User', UserSchema); }; ``` 4. 使用 Model 进行增删改查操作。在 Controller 中引入 Model,并使用相应的方法来操作数据库。例如,在 `app/controller/user.js` 文件中编写以下代码: ```javascript // app/controller/user.js const Controller = require('egg').Controller; class UserController extends Controller { async create() { const { ctx } = this; const { name, age, email } = ctx.request.body; const user = new ctx.model.User({ name, age, email, }); try { await user.save(); ctx.body = 'User created successfully'; } catch (error) { ctx.body = error; } } async find() { const { ctx } = this; try { const users = await ctx.model.User.find(); ctx.body = users; } catch (error) { ctx.body = error; } } // 其他操作方法类似 } module.exports = UserController; ``` 这样,你就可以在 Egg.js 中使用 MongoDB生成表,并进行相应的增删改查操作了。需要注意的是,上述代码仅为示例,你可能需要根据你的实际需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值