So far, throughout my Node.js learning journey it's been quite fun. Me personally, I love to have my code organized. So, what I've done was mimic rails like architecture. I created and app folder, and inside this app folder I have a few other folders such as models, controllers, routes, middleware, and tests. I didn't use 100% of rails architecture but just enough to help me have an organized directory structure.
I come from a rails background so seeing the way Node deals with Models is a tad different, but not "oh my god, what the hell" different. Say we had a model named 'Note' representing something that a user writes. The note has a title, and content. In rails you would define your schema within a migration file like so:
def change create_table :notes do |t| t.string :title t.string :content end end
You would then go inside your note.rb file to define any validations and associations like so:
class Notes < ActiveRecord::Base validates :title, :content, presence: true belongs_to :user end
This is what it would look like in rails. Pretty straightforward huh? Now, let's check out modeling inside of a Node project.
You define the schema and validations within the note.js file. By the way I'm using the MongoDB database which is a non-relational database. You associate your models using referencing and embedding as opposed to belongs to or has many. Let's define a Note schema and validations. I'll be using the Joi npm package to assist in the validation of a note.
FYI, the validations defined within the Schema will do just fine. Using the joi package is a plus, setting up some validations on the client side.
To associate a note with a User, you can simply embed the schema into a user. So a user will have an array of NoteSchemas (Every created note).
It'll look a little something like this:
If you take a look at the notes property defined in the UserSchema, we set the type to [NoteSchema]. This indicates that the user "has many" notes.