【问题标题】:mongodb schema use for multiple collectionsmongodb 模式用于多个集合
【发布时间】:2022-11-12 10:56:26
【问题描述】:

我在一个文件中有一个 mongodb 的架构,我将该架构用于多个集合。我目前必须复制架构文件并更改 2 个值才能使其正常工作。

我正在寻找一种使 1 模式动态化的方法,以便在保存到 mongodb 时可以更改网络和 dex

这是我的架构。

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
    };
};

在我保存交易的地方,我想定义要保存到的数据库和集合。

如果有人知道如何做到这一点,我喜欢获得一些信息。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    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;
        };
    };
    

    现在我可以为多个数据库和集合使用 1 个模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 2020-02-16
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2016-01-28
      相关资源
      最近更新 更多