W
W
wiyod2017-11-14 20:54:43
MongoDB
wiyod, 2017-11-14 20:54:43

Multiple databases in one NodeJS project with Mongoose?

Is it possible to use multiple Mongo databases in one NodeJS application?
How to switch between them? How to organize the code?
Here is an example of what I have now:

mongoose.connect(process.env.DATABASE, { useMongoClient: true, autoReconnect: true, reconnectTries: 30, reconnectInterval: 1000 }, )
  .then(() => {
    console.log('Connected to Server successfully!')
  })
  .catch((err) => {
    console.log(` → ${err.message}`)
    return err
  })

So I connect to process.env.DATABASEand a collection is already created there according to my model.
But what if I want to use the same model BUT in relation to several databases?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Abcdefgk, 2017-11-15
@Abcdefgk

Can. But it won't work.

R
RidgeA, 2017-11-14
@RidgeA

I'm at a loss as to why the same model is in different databases (it's clear if there are different models in different databases), but you can
1. create multiple database connections using mongoosejs.com/docs/api.html#index_Mongoose-create ...
2. and then within this connection create a model mongoosejs.com/docs/api.html#connection_Connection...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question