Skip to content
Advertisement

Using new collections for each user

I am building an Expense Tracking app using Node.js where all the Income and Costs should get saved in a database.

My idea is to create a new collection for each registered user and save all their income/cost actions in that collection.

The things i would like to consider before writing it are:

  • how do i name the collections
  • Efficiency of this method
  • is it even secure
  • how do i save their data when they login from an another device
  • can two users have the same collection name causing them to save their actions in one collection
  • are there any better ways to do this

What i came up with to solve it was to make a model which takes the given company/user name to create a collection.

const mongoose = require('mongoose');
const bcrypt = require ('bcrypt');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    userName: {
        type: String,
        required: true,
        unique: true
    },
    userPass: {
        type: String,
        required: true
    },
    userEmail: {
        type: String,
        required: true,
        unique: true
    }
}, { timestamps: true });

UserSchema.pre('save', async function (next) {
    try {
        const hashed = await bcrypt.hash(this.userPass, 10)
        console.log('saved user with hashed password.')
        this.userPass = hashed
        next();
    } catch {
        next(error)
    }
})

const User = mongoose.model(userName, UserSchema);

module.exports = User;

And that collection can only be accessed by the one who has the password for that unique name.

So what i would like to ask is: Are there any better ways to do this?

Advertisement

Answer

The problem was the way i was trying to save the income/expense actions. My idea was to make an individual collection for each user which would have required me to name every collection unique.
From what i understand it would also not be easily manageable on a large scale since every user is supposed to have its own collection which can stack up to hundereds of collections.

Like Maximilian mentions it’s far more easy and managaeble to make one collection for all the income/expense actions and reference each document to a specific user.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement