mongoose 用于多个集合mongodb模式

fumotvh3  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(145)

我在一个文件中有一个mongodb的模式,我在多个集合中使用了这个模式。我现在必须复制这个模式文件并修改2个值才能使它工作。
我正在寻找一种方法,使1模式的动态,这样我就可以改变网络和dex时,保存到mongodb
这是我的图式。

const db = mongoose.createConnection(database);
const Transactions = db.useDb('BSC'); // each network gets its own database

const txSchema = new mongoose.Schema({
    uniquePoint:{
        type: String,
        required: true,
        index: true,
        unique : true,
    },
    pairAddress: {
        type: String,
        required: true,
    }
},{collection: 'PCS'}); // each swap gets its own collection

export default Transactions.model('TX', txSchema);

我搜索了很多,但没有找到我需要的。我需要能够更改db.useDb('')和{collection:''}动态更新。
这就是我如何使用模式进行保存

import Transactions from '../models/BSC/tx_PCS.js';

export function saveTX(data, network){
    try{
        const newTX = new Transactions(data);
        newTX.save((err)=>{
            if(err){
                if(err.code == 11000) return;
                return console.log(err, data.pairAddress);
            };
            return;
        });
    } catch(err){
        return
    };
};

在保存事务的位置,我希望定义要保存到的数据库和集合。
如果有人知道怎么做,我喜欢得到一些信息。

ecr0jaav

ecr0jaav1#

我通过将模式导出为函数并使用参数更改数据库和集合来解决这个问题。

export default function(dex, network){
    const db = mongoose.createConnection(localDatabase); // connect to database
    const transactions = db.useDb(network); // change database
    const txSchema = new mongoose.Schema({
        uniquePoint:{
            type: String,
            required: true,
            index: true,
            unique : true,
        },
        DEX:{
            type: String,
        },
        network:{
            type: String
        },
    },{collection: dex}); // dynamic collection

    return transactions.model('TX', txSchema);
};

正在导入架构。

import tx from '../models/tx.js';
export function saveTX(data, network){
    const TX = tx(data.DEX, data.network);
    
    try{
        const newTX = new TX(data);
        newTX.save((err)=>{
            if(err){
                if(err.code == 11000) return;
                return console.log(err, data.pairAddress);
            };
            return;
        });
    } catch(err){
        return;
    };
};

现在,我可以对多个数据库和集合使用一个模式。

相关问题