skip to Main Content

I am using NuxtJS 3 and Vue 3 and I am connecting to a single mongoDb database without problem. I would like to connect at the same time to another database, where I will store and retrieve data.

My question is: How can I implement that and selecting each database in the server routes?

I am using mongoose!

2

Answers


  1. Chosen as BEST ANSWER

    .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


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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search