skip to Main Content

I want to create a seperate isolated database for every user on registration and only that person (authenticated) can be able to see his database and edit,delete,update,create posts in it. Thanks.

I want to create a seperate isolated database for every user on registration and only that person (authenticated) can be able to see his database and edit,delete,update,create posts in it. Thanks.

2

Answers


  1. Basically you will need a main database.

    In this main database you will have two collections. The first collection will register the users and in the second collection the database names of those users will be related to the user id, and every time you create a new user you will also create a new database linked to the user id.

    Next you will create two database connection variables, you will have something like this:

    const authConnection = mongoose.createConnection("your main db name", options);
    
    const mainConnection = async (dbname)=> {
      return await mongoose.connect(dbname,{});
    }
    

    The authConnection variable you will use in your user model will look something like:

    export const User = authConnection.model('your collection name', schema);
    

    Now when you login you will get the authenticated user id and make a query in the database collection passing filter the user id will be something like:

    const database = await UserDatabase.findOne({user_id: "your user id"})
    

    And then you just need to call your mainConnection function passing the database name by pair it will be something like:

    await mainConnection(database.name);
    

    That way every time you authenticate it will create the database and automatically connect to it.

    Just don’t forget to close the connection before you open another one.

    I Hope this helps.

    Login or Signup to reply.
  2. you cannot have multiple database connections but can have multiple collections ,on a single server.

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