I have reached the URL Shortener project and I love the journey so far. I was hoping I could implement some ‘Best practices’ in this project and not just have a working code and therefore would like your feedback on how I have done so far and how do I go about this in the future.
I understand this looks kinda big - but it essentially boils down to 2 questions.
Here is my entire code so-far, note: it’s partially complete --> https://glitch.com/edit/#!/rune-slope
What I need feedback/help on:
- When using mongoose, I understand you create a Schema and a Model (and that you can create DB entries by creating instances of this Model class and using save() function ). Do I ever have to export the Schema object? Am I correct in my assumption that you can simply export the Model object and create entities with it (and never bother with exporting it at all!).
Why I am asking this: Model and Schema are disparate constructs, right now, I am creating both of them in the same .js file. I feel like I am doing something wrong with abstraction here.
Code:
const conn = require('./conn'); //Conn is the Mongoose object exported
//like so --> module.exports = mongoose;
const URLCollection = conn.Schema({ // Do I need to bother exporting this?
URL: {type : String, required: true, index: true},
shortURL: {type : String, required: true}
});
const URLShortenerModel = conn.model('URLCollection', URLCollection); // I can simply create objects with this right?
module.exports = URLShortenerModel;
- I don’t really understand how JS classloading works, but when I export the variable, it is fine if it is a URLShortenerModel is a const right? I mean, the JS file is going to loaded into memory for every request (Or am I completely wrong here). Any good reason why it should not be a const and should be a let or var instead?
Thank you for your help. Kinda new to JS Any additional feedback welcome and appreciated!