0

I'm working through this Node ToDoList App API tutorial. It has one model, one controller and one routes file: https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd

Repo: https://github.com/generalgmt/RESTfulAPITutorial

In the model, we use mongoose to define TaskSchema and export mongoose.model('Tasks', TaskSchema);

In the controller, we create a Task var, set equal to mongoose.model('Tasks', TaskSchema); and use it to define several controller methods.

The server.js requires Task from the model, but never seems to use it for anything. The server also requires the routes file, which in turn require the controller, but I can'a see how they ever interact with the model.

How does the rest of the app know about the model? How does the controller know the schema for Task? Is this all mongoose magic?

David Kennell
  • 1,147
  • 2
  • 11
  • 22

1 Answers1

1

The Task schema is being called in the controller in line #4 https://github.com/generalgmt/RESTfulAPITutorial/blob/master/api/controllers/todoListController.js#L4

It does seem like the model being required in server.js is not used.

Server.js or routes don't need to interact with the schema, as all the methods required to interact with the schema are required in the Task constructor. The controller knows about the Task schema because it is being required in the controller.

  • Okay, so if two files require mongoose from the same package.json, they're given the same mongoose instance and as such the same database connection? – David Kennell Oct 10 '17 at 21:14
  • My problem is understanding how ` Task = mongoose.model('Tasks');` is requiring anything. To me, that looks like creating a model but, but without any schema. – David Kennell Oct 10 '17 at 21:27
  • Oh, I see. So the thing is that schemas define the structure of the collection you need, while the model actually gives you an interface to interact with it. – Luis Diego Hernández Oct 11 '17 at 17:34
  • 1
    `Require` doesn't really "require" modules from `package.json`; package.json stores metadata about the project and handles dependencies, but requires are resolved from within the core of the application or the path you pass to it. And yes, you'd get the same instance because modules are singletons most of the time. – Luis Diego Hernández Oct 11 '17 at 17:43