In this post, we’re going to be creating a sample comments system using Node, Express and Mongoose. Mongoose provides an object oriented interface for using MongoDB in Node. Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. If you are not familiar with Mongoose I suggest you read the docs here.

Getting Started
For this tutorial, you will need Express and MongoDB installed on your machine. I covered this in a previous tutorialso refer to it in case you don’t already have them installed.

Mongoose
To install Mongoose, open your terminal screen and enter the following:

$ npm install mongoose

To automatically build out an application template for your application, navigate to the directory where you wish to create your application and run the following code:

mkdir MongooseExample
cd MongooseExample
express -c stylus
npm install -d

What this does:

  • create the directory for your application.
  • create your application template using the jade template engine and the stylus css engine.

You should now be able to run your application and see a generic Express application.

node app.js

Navigate to http://localhost:3000

Installing Dependencies
First we need to add our dependency for Mongoose. Open your package.json and add the following code:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "dependencies": {
    "express": "3.1.0",
    "jade": "*",
    "stylus": "*",
    "mongoose" : "3.2.0"
  }
}

Everything should have already been there with the exception of "mongoose" : "3.2.0". Once you have saved the file run the following code to download and install the nodejs client for mongoose:

npm install -d

The Code
db.js
Now we’re going to create a file called db.js to configure MongoDB and our schema.

var mongoose = require( 'mongoose' );
var Schema   = mongoose.Schema; var Comment = new Schema({
    username : String,
    content  : String,
    created  : Date
}); mongoose.model( 'Comment', Comment ); mongoose.connect( 'mongodb://localhost/express-comment' );

Save this file in the same directory as app.js. The first thing we do is include mongoose and get a reference to schema. Everything in mongoose is derived from a schema. Next, we create our Comment schema and compile it into a model. Last we open a connection to our express-comment database on our locally running instance of MongoDB.

app.js
Open app.js and add require( './db' ); at the top of the file. It should look this:


/**
 * Module dependencies.
 */ require( './db' ); //for mongoose. Require this first!!! var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path'); var app = express(); app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
}); app.configure('development', function(){
  app.use(express.errorHandler());
}); app.get('/', routes.index);
app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

index.js
Open index.js and add the following code:

var mongoose = require( 'mongoose' );
var Comment = mongoose.model( 'Comment' ); exports.index = function ( req, res ){
  Comment.find( function ( err, comments, count ){
    res.render( 'index', {
        title : 'Comment System with Mongoose and Node',
        comments : comments
    });
  });
}; exports.create = function ( req, res ){
  new Comment({
    username : req.body.username,
    content : req.body.comment,
    created : Date.now()
  }).save( function( err, comment, count ){
    res.redirect( '/' );
  });
};

The first thing we do is require mongoose and the Comment model before we can use it. The index function is replaced with one that queries the database for comments and returns them to the index page. Comment.find is used to pull all comment collections. The create function saves a new comment from form values. We’ll create the form in a minute. First, add the following line to app.js: app.post( '/create', routes.create );
It should now look like this:

app.get('/', routes.index);
app.post( '/create', routes.create );

index.jade
Open index.jade and add the form and a loop to show the comments under the form.

extends layout

block content
  h1= title
  div.addCommentForm
        form( method="post", action="/create")
            div
                div
                    span.label Name :
                    input(type="text", class="nameTxt", name="username")
                div
                    span.label Comment :
                    textarea(name="comment")
                div#addCommentSubmit
                    input(type="submit", value="Save")
  br
  br
  #comments
    - each comment in comments
      div.comment
        div.name= comment.username
        div.created_at= comment.created
        br
        div.content= comment.content
        hr
 

style.styl
You will need to pretty up the page so open style.styl and add the following code:

body
  padding: 50px
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif
a
  color: #00B7FF
.addCommentForm
    width 450px
  input[type =text]
    width 200px
    margin-left 38px
  textarea
    width 200px
    margin-left 10px
  input[type =button], input[type =submit]
    clear both
    margin-left 85px
    display block
  .label
      text-align right !important
      display block
      float left
#comments
  .name
    float left
  .created_at
    float right
  .content
    clear both

Now re-run the application and you should be able to add comments which will display under the form. Navigate to localhost:3000 and make sure you have MongoDB up and running.

node app.js

Download the source code at https://github.com/ijason/NodeJS-Mongoose

Getting Started with Mongoose and Node.js – A Sample Comments System | Dev Notes的更多相关文章

  1. node.js delete directory & file system

    node.js delete directory & file system delete a not empty directory https://nodejs.org/api/fs.ht ...

  2. mongoose - 让node.js高效操作mongodb

    Mongoose库简而言之就是在node环境中操作MongoDB数据库的一种便捷的封装,一种对象模型工具,类似ORM,Mongoose将数据库中的数据转换为JavaScript对象以供你在应用中使用. ...

  3. MONGOOSE – 让NODE.JS高效操作MONGODB(转载)

    Mongoose库简而言之就是在node环境中操作MongoDB数据库的一种便捷的封装,一种对象模型工具,类似ORM,Mongoose将数据库中的数据转换为JavaScript对象以供你在应用中使用. ...

  4. [Debug] Debug Node.js Application by using Chrome Dev tools

    For example you have a server.js file, and you want to debug some problems; What you can do is: node ...

  5. 前端(Node.js)(1)-- 初识Node.js

    1.认识 Node.js 诞生.发展.应用现状.生态圈等方面 1.1. 2008年 RyanDahl的目标是创建一个易扩展.适用于现代Web应用通信的服务器平台 1.2.国内外的应用情况 Linked ...

  6. Node.js NPM Tutorial

    Node.js NPM Tutorial – How to Get Started with NPM? NPM is the core of any application that is devel ...

  7. 基于Node.js + jade + Mongoose 模仿gokk.tv

    原文摘自我的前端博客,欢迎大家来访问 http://www.hacke2.cn 关于gokk 大学的娱乐活动基本就是在寝室看电影了→_→,一般都会选择去goxiazai.cc上看,里面的资源多,质量高 ...

  8. Node.js 入门:Express + Mongoose 基础使用

    前言 Express 是基于 Node.js 平台的 web 应用开发框架,在学习了 Node.js 的基础知识后,可以使用 Express 框架来搭建一个 web 应用,实现对数据库的增删查改. 数 ...

  9. [js高手之路]Node.js+jade+mongodb+mongoose实现爬虫分离入库与生成静态文件

    接着这篇文章[js高手之路]Node.js+jade抓取博客所有文章生成静态html文件继续,在这篇文章中实现了采集与静态文件的生成,在实际的采集项目中, 应该是先入库再选择性的生成静态文件.那么我选 ...

随机推荐

  1. 【Binary Tree Inorder Traversal】cpp

    题目: Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary ...

  2. JavaScript继承学习笔记

    JavaScript作为一个面向对象语言(JS是基于对象的),可以实现继承是必不可少的,但是由于本身并没有类的概念,所以不会像真正的面向对象编程语言通过类实现继承,但可以通过其他方法实现继承.(jav ...

  3. python 可变参数

    原文地址:http://docs.pythontab.com/python/python3.4/controlflow.html#tut-functions 一个最不常用的选择是可以让函数调用可变个数 ...

  4. 802.11 wireless 五

    802.11 wireless 5CSMA/CA,采用倒计时的方法,退避的时间(当年时间+duration 为发送时间,每一个帧会有一个duration,这个位叫做duration[n.持续]) PS ...

  5. 【Lua】Lua中__index与元表(转)

    转载于:http://blog.csdn.net/xocoder/article/details/9028347 Lua的表本质其实是个类似HashMap的东西,其元素是很多的Key-Value对,如 ...

  6. ubuntu1404_server搭建lamp

    ubuntu server版可直接一键安装lamp环境 apt-get install lamp-server^ 根据提示输入所需设置密码即可,其配置文件跟编译安装的apached等区别很大 apac ...

  7. 用fscanf()从文件取数据时,如何判断文件结束

    例子:从键盘输入若干行字符(每行长度不等),输入后把它们存储到一磁盘文件中.再从该文件中读入这些数据,将其中小写字母转换成大写字母后再显示屏上输出. 有两种方法 1.使用feof()函数 #inclu ...

  8. iOS 面试题

    1.Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么? 答:不可以,可以实现多个接口:category是分类,,一般情况下分类 ...

  9. Sqli-labs less 41

    Less-41 此处与less-39是一致的,区别在于41错误不回显.所以我们称之为盲注. Payload: http://192.168.11.189/sqli-labs/Less-41/index ...

  10. 制作类似DataGrid自定义控件

    首先看一下.net自带的DataGrid,想想如何应该怎样才能实现那样的展现形式. 1)需要以网格形式显示内容. 2)网格的宽度.高度可以定义. 3)可以显示滚动条. 4)单击可以选中某个单元格. 当 ...