1

I am looking for a way to use 1 schema for multiple databases and collections. I have 3 different databases and each holds 3 to 4 collections, which use all the same schema. I started just duplicating the schema for each collection and database, but that will add up to the amount of work. then I tried to export a function that returns the schema with set parameter, but I think that creates a new connection each time I call the function and eventually I get error. I can not find how to solve my problem the right way. Please someone can help me out a little.

What I currently try to use.

import mongoose from 'mongoose';
import Config from '../components/config.js';


const {database, localDatabase} = Config();


export default function(dex, network){
    const db = mongoose.createConnection(localDatabase);
    const transactions = db.useDb(network); // each network gets its own database
    const txSchema = new mongoose.Schema({
        uniquePoint:{
            type: String,
            required: true,
            index: true,
            unique : true,
        },
        version:{
            type: String,
            required: true,
        },
        network:{
            type: String,
            required: true,
        },
    },{collection: dex}); // each dex gets own collection

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

But this seems to give error after a while "MongoNetworkError: connect EADDRNOTAVAIL"

Mayga Fatmawati
  • 101
  • 2
  • 7
  • Does this answer your question? [Mongoose how to use same schema for different collections, but still be able to update those collections individually](https://stackoverflow.com/questions/49751908/mongoose-how-to-use-same-schema-for-different-collections-but-still-be-able-to) – rickhg12hs Nov 14 '22 at 09:12
  • This unfortunately does not work for me. With the example I can create a model for each collection, but I can not connect to different databases. I need to call the save function and there I define what database and collection to save to. – Mayga Fatmawati Nov 14 '22 at 09:46
  • I'm not a mongooser so I hesitate to answer, but won't you need a separate [`Connection` object](https://mongoosejs.com/docs/api/connection.html) for each database? Seems like you should be able to reuse the schema for each. – rickhg12hs Nov 14 '22 at 10:00
  • Yeah, I think that's right, but I can not find anything that gives me some info on how to do this. I basically have 1 save function and 1 schema. in the save function I would like to define what database and what collection to save. – Mayga Fatmawati Nov 14 '22 at 10:12
  • Maybe [this answer](https://stackoverflow.com/a/50818384/1409374) has some useful info for you? ... or perhaps some other answers to the same question? – rickhg12hs Nov 14 '22 at 10:15

0 Answers0