Do we need to write a model every time we need to save or update an item in the database?

tdd

#1

Question

Do we need to write a model every time we need to save or update an item in the database?

Answer

No, remember about collections? (if not much, you can revisit this lesson) Collections are the equivalent of a table in the database, they contain all the documents of one kind (ish), mainly all the documents we want in that collection.
A model, is Mongoose’s object constructor that creates a collection in the MongoDB database, so each model can be the equivalent of a collection. Without that model we do not have a location where to specifically save documents on the database, but we only need one per collection, not per document that we want to save, for example, if we wanted to create a collection of recipes in our database, we will have a recipeSchema:

const recipeSchema = new mongoose.schema({
  recipe_name: String,
  ingredients: Mixed,
  date_created: Date,
  preparation: String  
})

And we will need a recipe model that will create a collection for our recipes:

const recipes = mongoose.model('Recipes', recipeSchema);

Now we can create or update as many documents in our 'Recipes' collection using the recipes model:

const axelsFamousPumpkinPie = {...} // I wouldn't give out my recipe XP

recipes.save(axelsFamousPumpkinPie); 
//now we can add as many recipes and we only neede one model.