MEAN,从MONGO DB里弄出点东东来啦,以REST风格显示JSON

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 最近一直在弄弄的。。。 javascript的风格弄熟了,我觉得肯定很快,,但心中有种感觉,DJANGO和MEAN这种结构,搞大的不行。 因为MVC这种结构感觉不如SPRING这些严谨,是不是我有偏见呢?水平不够呢?不强制就不弄呢? db层写法: /** * Created by sahara on 2016/7/5.

最近一直在弄弄的。。。

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;

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。   相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
JSON 算法 数据挖掘
python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)
python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)1. 场景描述一直做java,因项目原因,需要封装一些经典的算法到平台上去,就一边学习python,一边网上寻找经典算法代码,今天介绍下经典的K-means聚类算法,算法原理就不介绍了,只从代码层面进行介绍,包含:rest接口、连接mpp数据库、回传json数据、下载图片及数据。
1181 0
|
关系型数据库 API PHP
如何禁用WordPress程序REST API功能且移除wp-json链接
WordPress是什么? WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。
1689 0
|
JSON API 数据格式
解决一个Django Rest Framework的JSON输出的小问题
由于前端用了vue.js作了数据的加载,如果同样的代码,那获取json中对象的信息显然就会发生问题。 解决BUG的时间来不及,也无法深入调试。可用以下代码,判断json中是否有存在对象来进行对象的赋值,可解决这个输出问题。
2389 0
|
JSON 网络架构 数据格式
算是帮华仔写的撸JSON文件,然后发到我的REST接口的PYTHON代码
很久没有写过类似的代码了,感觉好陌生。。。 #!/usr/bin/python #coding:utf-8 import json import getopt import sys import requests #获取命令行参数 def get_opt(): ...
1049 0
|
JSON 前端开发 网络架构
asp.net mvc实现rest风格返回json
实现类似:http://localhost:1799/rest/person/1方式返回一个json内容: 在asp.net mvc中新建一个control rest,然后在其中新增方法: 1 public IAction...
1217 0
|
XML JSON API
Delphi XE程序设计系列 1-主从架构, 多层到JSON和REST
Delphi XE程序设计系列 1-主从架构, 多层到JSON和REST      从桌面开发,主从架构,一直到多层架构,虽然都是广泛被接受的观念和技术,但在信息技术的实作上却从不是开放, 相容的世界。
1495 0
|
3月前
|
JSON PHP 数据格式