Full stack app where users can login, post and review campgrounds, and comment.
node.js 是一个 JavaScript 运行时,它让 JavaScript 脱离了浏览器环境,可以直接在计算机上运行,如访问 PC 其他组件/在 server 端(其他的电脑上)运行,所以让 JS(或者说框架 Express) 可以作为后端语言,极大地拓展了 JavaScript 用途。
node.js 优点:有非阻塞,事件驱动 I/O 等特性,从而让高并发(high concurrency)在的轮询(Polling)和 comet 构建的应用中成为可能
npm 是 NodeJS 的包管理器(NodeJS package manager),一般是随同 NodeJS 一起安装,能解决 NodeJS 代码部署上的很多问题:
- 在 Node.js 上开发时,会用到很多别人已经写好的 javascript 代码,如果每当我们需要别人的代码时,都根据名字搜索一下,下载源码,解压,再使用,会非常麻烦——于是就出现了包管理器 npm。大家把自己写好的源码上传到 npm 官网上,如果要用某个或某些个,直接通过 npm 安装就可以了
注意: 如果您想更新到 XXX modules 的最新主版本(例如从 5.x.x 更新到 6.x.x),则需要手动更新 package.json 文件中的版本范围,然后再运行 npm update 命令,才能生效。
route 路由,在 web 开发中,“route”是指根据 url, 分配到对应的处理程序。 就是一个路径的解析,根据客户端提交的路径,将请求解析到相应的控制器上。 a mechanism where HTTP requests are routed to the code that handles them. To put simply, in the Router you determine what should happen when a user visits a certain page.
Express, mongoose, ejs
Routes are the program(code) that are responsible for listening and receiving requests and then deciding what to send back.
路由:url 对应分配到的处理程序
REST, Representational State Transfer 是一种网络架构的风格,具有这种风格的系统可以称为是 RESTful 的。 或者更直白地說:Restful is just a pattern for defining routes, by mapping HTTP requests(C 端发起的请求) to CRUD operations(S 端处理请求的方式).
直观地从 URL 、发送的http 请求(GET、POST、DELETE...)、以及请求所得到的状态码,就知道做了什么操作,结果如何
4 basic types of (DB) actions: Create, Read, Update, and Delete. 增删改查
(上文的 7 routes 实则是 CRUD: Read 对应 2 个 + C U D 3 个 + Create 和 Update 需先用 Read 2 个, 但得根据实际的业务需求来定义 routes,所以routes 的组合并不唯一)
mongoose: an Object Data Modeling (ODM) Library for MongoDB and Node.js, provides a straight-forward, schema-based solution to MODEL application data.
是针对 MongoDB 操作的一个对象模型库
- 和 mongoDB建立连接
- 封装了 MongoDB 对文档的的一些增删改查等常用方法
让NodeJS 操作 Mongodb 数据库变得更加灵活简单
we take the campground in the ID and just put it before all of the routes that have to do with comments.
Why? Dependency Because a comment is dependent on a campground. They are inherently linked. Inside the CREATE, we're not just going to make a comment: make a comment + then associate it with the campground.
So we're going to have to do a find by ID for camp ground.
By following this pattern, you don’t have to reinvent the wheel every time you build a new CRUD app. The routes and method names have already been decided so that you can run the action by directly editing URL !!!
- one to one
- one to many
- many to many
focus on one to many here exmaple: user - entire posts
way1: Embedding Entire Data in JS array [] (No referencinng ID!) -> Embedded data is not a doc in DB
very straightfoward
- build reference in schema first
-
in .save() method's callback after pushing, its return value "user" shows only post IDs
-
use findOne(userName: userName).populate("post").excute(func(err, user)) to show complete data in referenced posts