最近一直在弄弄的。。。

javascript的风格弄熟了,我觉得肯定很快,,但心中有种感觉,DJANGO和MEAN这种结构,搞大的不行。

因为MVC这种结构感觉不如SPRING这些严谨,是不是我有偏见呢?水平不够呢?不强制就不弄呢?

db层写法:

/**
 * Created by sahara on 2016/7/5.
 */

var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/Loc8r';
var gracefulShutdown
mongoose.connect(dbURI);

mongoose.connection.on('connected', function () {
    console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
    console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose disconnected');
});

var readLine = require ("readline");
if (process.platform === "win32"){
    var rl = readLine.createInterface ({
        input: process.stdin,
        output: process.stdout
    });
    rl.on ("SIGINT", function (){
        process.emit ("SIGINT");
    });
}

gracefulShutdown = function (msg, callback) {
    mongoose.connection.close(function () {
        console.log('Mongoose disconnected through ' + msg);
        callback();
    });
};

process.once('SIGUSR2', function () {
    gracefulShutdown('nodemon restart', function () {
        process.kill(process.pid, 'SIGUSR2');
    });
});
process.on('SIGINT', function () {
    gracefulShutdown('app termination', function () {
        process.exit(0);
    });
});
process.on('SIGTERM', function() {
    gracefulShutdown('Heroku app shutdown', function () {
        process.exit(0);
    });
});

require('./locations');

数据库定义:

/**
 * Created by sahara on 2016/7/5.
 */

var mongoose = require('mongoose');

var openingTimeSchema = new mongoose.Schema({
    days: {type: String, required: true},
    opening: String,
    closing: String,
    closed: {type: Boolean, required: true}
});

var reviewSchema = new mongoose.Schema({
    author:String,
    rating: {type: Number, required: true, min: 0, max: 5},
    reviewText: String,
    createdOn: {type: Date, "default": Date.now}
});

var locationSchema = new mongoose.Schema({
    name: {type: String, required: true},
    address: String,
    rating: {type: Number, "default": 0, min: 0, max: 5},
    facilities: [String],
    coords: {type: [Number], index: '2dsphere'},
    openingTimes: [openingTimeSchema],
    reviews: [reviewSchema]
});

mongoose.model('Location', locationSchema);

路由层写法:

var express = require('express');
var router = express.Router();
var ctrlLocations = require('../controllers/locations');
var ctrlReviews = require('../controllers/reviews');

//locations
router.get('/locations', ctrlLocations.locationsListByDistance);
router.post('/locations', ctrlLocations.locationsCreate);
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
router.put('/locations/:locationid', ctrlLocations.locationsUpdateOne);
router.delete('/locations/:locationid', ctrlLocations.locationsDeleteOne);

//reviews
router.post('/locations/:locationid/reviews', ctrlReviews.reviewCreate);
router.get('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewReadOne);
router.put('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewUpdateOne);
router.delete('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewDeleteOne);

module.exports = router

控制器写法:

/**
 * Created by sahara on 2016/7/6.
 */

var mongoose = require('mongoose');
var Loc = mongoose.model('Location');

var sendJsonResponse = function(res, status, content) {
    res.status(status);
    res.json(content);
};

module.exports.locationsListByDistance = function (req, res) {
    sendJsonResponse(res, 200, {"status" : "success"});
};

module.exports.locationsCreate = function (req, res) {
    sendJsonResponse(res, 201, {"status" : "success"});
};

module.exports.locationsReadOne = function (req, res) {
    if (req.params && req.params.locationid){
        Loc
            .findById(req.params.locationid)
            .exec(function(err, location){
                if (!location) {
                    sendJsonResponse(res, 404, {
                        "message": "locationid not found"
                    });
                    return;
                } else if (err) {
                    sendJsonResponse(res, 404, err);
                    return;
                }
                sendJsonResponse(res, 200, location);
            });
    } else {
        sendJsonResponse(res, 404, {
            "message": "no locationid in request"
        });
    }
};

module.exports.locationsUpdateOne = function (req, res) {
    sendJsonResponse(res, 200, {"status" : "success"});
};

module.exports.locationsDeleteOne = function (req, res) {
    sendJsonResponse(res, 204, {"status" : "success"});
};

app.js的改装:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('./app_api/models/db');

var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
var users = require('./app_server/routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/api', routesApi);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

MEAN,从MONGO DB里弄出点东东来啦,以REST风格显示JSON的更多相关文章

  1. mongo DB for C#

    (1)Download the MongoDB C#驱动. http://www.nuget.org/packages/mongocsharpdriver/. (2) Add Reference to ...

  2. json是个啥东东

    xml 不用说 只要是搞web开发的 没听说谁不知道的 一种类似数据传输格式定义的语言 但是他却不是一个真正的轻量级的东西 其他的不说 只要传输一点很少的数据 经过他那左括号右括号 还有什么属性 一包 ...

  3. 长见识了,知道了collected和Graphite 这两个东东

    今天下午的讨论会议中,听到了两个名词collected和Graphite这是神马东东,以前在bingo的时候也没听说过,开完会下去查了下.原来他两是监控系统的啊.以前也从来没做过系统监控方面的项目,这 ...

  4. Mongo DB 2.6 需要知道的一些自身限定

    在现实的世界中,任何事情都有两面性,在程序的世界中,亦然! 我们不论是在使用一门新的语言,还是一门新的技术,在了解它有多么的让人兴奋,让人轻松,多么的优秀之余,还是很有必要了解一些他的局限性,方便你在 ...

  5. Mongo DB Study: first face with mongo DB

    Mongo DB Study: first face with mongo DB 1.  study methods: 1.  Translate: I am the mongo DB organiz ...

  6. BPEL是个什么东东

    研究团队有个做智能服务组合的,其中用到叫BPEL的东西,因为全称是Business Process Execution Language,译成中文就是商业执行过程语言,这个东东的是整合SOA的一个执行 ...

  7. SQLSERVER 里经常看到的CACHE STORES是神马东东?

    SQLSERVER 里经常看到的CACHE STORES是神马东东? 当我们在SSMS里执行下面的SQL语句清空SQLSERVER的缓存的时候,我们会在SQL ERRORLOG里看到一些信息 DBCC ...

  8. mongo db 分享 ppt

    在公司内部的mongo db的ppt.初步进阶 http://files.cnblogs.com/files/yuhan-TB/mongoDB.pptx

  9. Mongo DB 安装-及分布式集群部署(初稿)

    一.安装步骤, 1, 下载最新的Mongo DB数据库:http://www.mongodb.org/downloads?_ga=1.44426535.2020731121.1421844747\ 下 ...

随机推荐

  1. markdown 常用语法总结 - 个人版

    这里并不是要总结所有的 markdown 语法,只是总结笔者自己撰写博客时常用的一些 markdown 语法. 1 图片设置 1.1 设置图片位置 利用markdown在编写文档时插入图片是默认靠左, ...

  2. ORA-01654_TableSpace空间不足问题处理

    操作环境:Windows Server 2008 R2,32位Oracle11g R2. 导入大批量数据时报如下错误信息: ORA-: 索引IOT.IDX_IOT_EQUIP_ID无法通过1024(在 ...

  3. leetcode523 Continuous Subarray Sum

    思路: 令sum[p]表示p位置的前缀和.如果sum[i] % k == sum[j] % k (j - i > 1),则存在子段(i, j]的和能够整除k. 实现: class Solutio ...

  4. es6数值扩展

    1. 二进制和八进制表示法 从 ES5 开始,在严格模式之中,八进制就不再允许使用前缀0表示,ES6 进一步明确,要使用前缀0o表示. ES6 提供了二进制和八进制数值的新的写法,分别用前缀0b(或0 ...

  5. 02使用常规步骤编译NanoPiM1Plus的Android4.4.2

    02使用常规步骤编译NanoPiM1Plus的Android4.4.2 大文实验室/大文哥 壹捌陆捌零陆捌捌陆捌贰 21504965 AT qq.com 完成时间:2017/12/5 17:51 版本 ...

  6. python 关于一个懒惰和非懒惰的

    >>> pa = re.compile(r'<.*>') >>> result = pa.findall('<H1>title</H1 ...

  7. Java屏幕截图及剪裁

    Java标准API中有个Robot类,该类可以实现屏幕截图,模拟鼠标键盘操作这些功能.这里只展示其屏幕截图. 截图的关键方法createScreenCapture(Rectangle rect) ,该 ...

  8. tensorFlow资源

    1,[莫烦]Tensorflow tutorials (Eng Sub) 神经网络 http://www.bilibili.com/video/av10118932/index_35.html#pag ...

  9. window下编写python脚本在linux下运行出错 usr/bin/python^M: bad interpreter: No such file or directory

    今天在windows下使用notepad++写了个python脚本,传到linux服务器执行后提示:-bash: ./logger.py: usr/bin/python^M: bad interpre ...

  10. RocketMQ学习笔记(14)----RocketMQ的去重策略

    1. Exactly Only Once (1). 发送消息阶段,不允许发送重复的消息 (2). 消费消息阶段,不允许消费重复的消息. 只有以上两个条件都满足情况下,才能认为消息是“Exactly O ...