Is it better to create, read, update, and delete documents with models or queries?

tdd

#1

Question

Is it better to create, read, update, and delete documents with models or queries?

Answer

We cannot solely say that models replace Mongoose queries, as a matter of fact, they are aided by a query system from Mongoose called Midleware which provide the same function as queries. Middleware is specified on the schema level, so when we create our methods we can use this functions to bring the changes to the database, for example in the case of an update, we can change the document, and then use .save() like in this example from this lesson:

magicItemSchema.methods.use = function(callback) {
  this.totalUnits = this.totalUnits - this.unitCost;
  return this.save();
}

To create a new document in the collection using models you could also implement save()
but it is better recommended to use create() query.

To read documents from the collection you need to use queries, but you can also do it from a model method like we did with findMostExpensive in a static method:

 magicItemSchema.statics.findMostExpensive = function(callback) {
  return this.findOne({}).sort('unitCost').exec(callback);
}

To delete there is a middleware function called remove(), and we could use it for example, if we wanted to findMostExpensiveAndRemove:

 magicItemSchema.statics.findMostExpensiveAndRemove = function(callback) {
  return this.findOne({}).sort('unitCost').remove();
}

How we decide to provide CRUD functionality when using Mongoose will depend on what our app’s purpose is, and what we need to handle data, sometimes using queries will be the best, others a mix between middleware model methods and queries will be more adequate.