简体   繁体   中英

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....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM