Understanding TodoMVC Example

泄露秘密 提交于 2019-12-04 05:52:47

This is one of the more confusing things to deal with when starting out in Node and Mongoose.

When you require('mongoose') for the first time, it creates a singleton instance of Mongoose - the same instance is returned every subsequent time you require it.

This makes it really easy to work with, but is a bit of 'magic' that's hard to understand at the beginning.

It means that when you call mongoose.connect("127.0.0.1", "todomvc", 27017); in app.js, it creates a connection that persists with the app.

It also means that mongoose.model('Todo', TodoSchema); makes the Todo model available in any other scope that calls require('mongoose'), via mongoose.model('Todo'). This could be var'd at the top of another file you require as in the example above, or the moment you need it in the middle of a callback.

This is how you get the Todo model into your routes.js, and a very good reason to ensure telling Mongoose about your models is one of the first things you do in your application.

To answer your questions regarding understanding scopes; each file you require effectively has its own scope and doesn't have access to anything except global objects like process. You have to require everything you want to work with, and can only pass variables in by calling functions or creating classes that are exposed via the exports object.

So for the actual example above there is no benefit in exporting the model from models.js as it's not subsequently referenced in app.'s where models.js is required. It's these lines in routes.js that make the Todo model available:

var mongoose = require('mongoose')
, Todo = mongoose.model('Todo'); // returns the Todo model that was registered by models.js

That's how Todo exists on this line:

crudUtils.initRoutesForModel({ 'app': app, 'model': Todo });

There's also no benefit (as far as I know) in wrapping the routes in an anonymous function as this is essentially provided by require.

You're going to want to check out Express.

Express is a minimal and flexible node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications.

A lot of what you copy and pasted is using the Express Scaffold - so a lot of it is pre constructed for you, you can check it here: http://expressjs.com/

I hope that points you in the right direction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!