Nodejs + express + jade + mongodb make a small album for my baby (2)-message board

Source: Internet
Author: User

In the previous article, the photo display and browsing functions are implemented. I will add a message function to this program. If you leave a message, it will definitely involve data persistence. In fact, for this small feature, you can use xml. However, to look taller, I decided to use mongodb for a try.

1. Install mongoose

Npm install mongoose

You can use npm to install npm directly.

Mongoose is a framework similar to ORM. It provides a Schema class to define data models for users, encapsulates CRUD operations, and helps you manage mongodb connections. You do not need to open them on your own, close the connection.

2. encapsulate mongodb operations

Create a models directory in the root directory

Add mongodb. js under models

var mongoose = require('mongoose');mongoose.connect('mongodb://localhost/mongodb1');exports.mongoose = mongoose;

Under modelsAdd the Message. js Model

Var mongodb = require ('. /mongodb '); var Schema = mongodb. mongoose. schema; // defines the message Model var messageSchema = new Schema ({userName: String, content: String, createTime: {type: Date, default: Date. now}); mongodb. mongoose. model ('message', messageSchema); var message = mongodb. mongoose. model ('message'); exports. add = function (userName, content, callback) {var msg = new message (); msg. userName = userName; msg. content = content; // save to db msg. save (function (err) {if (err) {console. log (err); callback (err) ;}else {callback (null) ;}}) ;}; exports. getAll = function (callback) {message. find ({}, null, {sort: {'createtime':-1 }}, callback );}

In this way, the message is added and all operations are obtained.

3. Add message. jade View
Extends layoutblock content div (class = 'Container') form (class = "form-horizontal" method = 'post') fieldset div (class = "form-group ") label (for = 'username' class = 'col-sm-4 control-label text-info') = 'name' div (class = 'col-sm-2 ') input (type = "text" id = 'username' name = 'username' class = 'form-control input-sm 'value = name required) div (class = "form-group") label (for = 'msg 'class = 'col-sm-4 control-label text-info ') = 'content' div (class = 'col-sm-6 ') textarea (id = 'content' name = 'content' class = 'form-control' required) div (class = "form-group") div (class = 'col-sm-offset-4 col-sm-6 ') input (type = "submit" class = 'btn btn-primary 'value = 'submit ') for msg in msgs div (class = 'row ') div (class = 'col-sm-4 text-right') div (class = 'col-sm-8 text-info') = msg. userName + ':' + msg. content script (src = "/jqBootstrapValidation. js ") script $ (function () {$ (" input, select, textarea "). not ("[type = submit]"). jqBootstrapValidation ();});

Here we still use bootstrap for front-end and jqBootstrapValidation for data verification.

4. Add a message. js route
Var msgDb = require ('.. /models/message'); var url = require ("url"); var querystring = require ("querystring"); exports. msgList = function (req, res) {var objectUrl = url. parse (req. url); var objectQuery = querystring. parse (objectUrl. query); var userName = objectQuery ['username']; // if a user name exists, it indicates that the user has already submitted the request and passed it to the view, in this case, you do not need to enter the user name msgDb again after refreshing. getAll (function (err, messages) {if (err) {console. log (err); // exception jumps to the error page re S. redirect ('/error');} else {res. render ('message', {title: 'My Little start', msgs: messages, name: userName}) ;}) ;}; exports. saveMsg = function (req, res) {var userName = req. body. userName; var content = req. body. content; console. log ('userid = '+ userName + 'content =' + content); msgDb. add (userName, content, function (err) {if (err) {console. log (err); res. redirect ('/error');} else {// saved successfully. Refresh the message interface and use ur L pass res. redirect ('/message? UserName = '+ userName );}});};

There are two methods: one is to save the post message data and the other is to display all the data.

4. register the message route in app. js
var message = require('./routes/message');app.get('/message', message.msgList);app.post('/message',message.saveMsg);
5. Running Effect

Demo URL: http://kklldog.chinacloudapp.cn: 8888/message

 

Finally, for my little stars, I would like to find a good pitfall in the Suzhou area.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.