javascript 我如何按照我的设计模式来使用mongoose?

68bkxrlz  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(96)

我有一个关于如何在我的结构模式上做一些事情的问题。我使用MongoDB作为数据库,Mongoose作为ORM。
基本上,我有以下的用户模型:

import { Schema, model } from 'mongoose'

export interface IUser {
    _id: string,
    email: string,
    name: string,
    password: string,
    picture: string,
    description: string,
    plans: [
        {
            name: string,
            price: string,
            monthsDuration: number,
        }
    ],
    role: string,
    balance: number,
    createdAt: Date,
}

const UserSchema = new Schema<IUser>({
    email: {
        type: String,
        index: true,
    },
    name: String,
    password: String,
    picture: String,
    description: String,
    plans: [],
    role: String,
    balance: Number,
    createdAt: {
        type: Date,
        default: Date.now
    }
})

const UserModel = model('pvf2_users', UserSchema)
export { UserModel }

然后,我有一个存储库,用于管理将新用户插入到数据库中:

import { User } from "@domain/entities/user.entity.js";
import { UserModel } from "@domain/models/user.model.js";
import { UserRepositoryInterface } from "@domain/repositories/user.repository.js";

export class UserDatabaseRepository implements UserRepositoryInterface {

    async insert(user: User): Promise<void> {
        await UserModel.create(user.data)
    }

}

问题是,假设我想从MongoDB更改为Postgres或任何其他数据库,因为我直接调用mongoose模式来运行查询,所以我必须更改所有处理数据库查询等的存储库,我猜这与我的设计模式不符。
我怎样才能把它建立在这样一种方式上,即我可以很容易地改变我的数据库,而不必重写每个处理查询的文件?这可能吗?

ujv3wf0j

ujv3wf0j1#

通过创建mongoose抽象类解决:

import mongoose from "mongoose"

export abstract class MongooseAbstract {

    public constructor(protected modelName: string) { }

    public async db_insert(data: any): Promise<any> {
        const creation = await mongoose.model(this.modelName).create(data)
        return creation
    }

    public async db_findOne(query: any): Promise<any> {
        const doc = await mongoose.model(this.modelName).findOne(query).lean().exec()
        return doc
    }

    public async db_find(query: any, limit = 15): Promise<any> {
        const docs = await mongoose.model(this.modelName).find(query).limit(limit).lean().exec()
        return docs
    }

    public async db_updateOne(id: string, doc: any): Promise<any> {
        const updatedDoc = await mongoose.model(this.modelName).findOneAndUpdate({ _id: id }, doc, { new: true }).lean().exec()
        return updatedDoc
    }

}

相关问题