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?