[Vuejs]-Connect to 2 different mongodb databases in Nuxt 3 / Vue 3 Application

0👍

Thanks for elaborating on your question, after making both connections to mongoose, you can use mongoose.connections to differentiate between your databases!

ex:

mongoose.connections[0] // Points to the first connection (mongoose.connect(config.mongodbUri))

mongoose.connections[1] // Point to your admin connection (mongoose.connect(config.mongodbUriAdmin))

To simplify this further, I would create a variable that holds these values so that you can use them in your routes without repeating code!

Like this:

const admindb = mongoose.connections[1] // Admin Database

Here’s a link to the documentation !
https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.connections

👤Kyrony

-1👍

.env file:

MONGODB_URI=mongodb+srv://<username>:<password>@<cluster>.puuwipp.mongodb.net/<db1>
MONGODB_URI_ADMIN=mongodb+srv://<username>:<password>@<cluster>.puuwipp.mongodb.net/<db2>

nuxt.config.ts:

    runtimeConfig: {
    mongodbUri: process.env.MONGODB_URI,
    mongodbUriAdmin: process.env.MONGODB_URI_ADMIN,
  }

server.index.ts:

  export default async (_nitroApp: Nitro) => {
  const config = useRuntimeConfig();

  try {
    mongoose.set("strictQuery", false);
    await mongoose.connect(config.mongodbUri);
    console.log("DB connection established");
    await mongoose.connect(config.mongodbUriAdmin);
    console.log("ADMIN DB connection established");
  } catch (e) {
    return e.message;
  }
};

But I do not know, how to define which db to use in mongoose models / in the server requests

Leave a comment