3Pi
3Pi

Reputation: 31

Mongoose and Typescript - Link a model to a specific mongoose connection

I defined a Model in a ts file. I would like to use a specific mongoose connection (not the default one) with that model. How can I associate my model to the connection ?

Excerpt form my TS file :

export interface iSuppliers extends mongoose.Document {
suppliers: string[];
fields: number[];  
}

export const supplierSchema = new mongoose.Schema({
    suppliers: {type:[String], required: true},
    fields: [Number]})
.index({suppliers: 1}); // Additional index

export const supplier = mongoose.model<iSuppliers>('supplier', supplierSchema);

In my server.ts file :

import {supplier} from '....';
....
let database_2 = mongoose.createConnection(....);

Nothing happens when I use my supplier model to find data. Obviously, I need to bind it to my database_2 connection ...

I am not sure about the way to that....

Upvotes: 0

Views: 762

Answers (1)

3Pi
3Pi

Reputation: 31

I found out my way...

I export a function that returns the model and use my connection as a parameter...

export function importedGameDatabase(mongooseConnection: mongoose.connection) { return mongooseConnection.model<iImportedGames>('importedGame', importedGamesSchema); } 

Upvotes: 1

Related Questions