Fork me on GitHub

RESTful Mongodb

Ref:The MongoDB 3.2 Manual

Ref:Mac OX上安装MongoDb

Ref:Creating RESTful APIs with Express 4

Ref:Build a RESTful API Using Node and Express 4

Ref:RESTful Example using ExpressJS + Node.js + MongooseJS

Ref:Mongoose学习参考文档——基础篇

Ref:MongoDB学习笔记(查询)

Ref:MongoDB限制查询返回的字段

Ref:http://mongoosejs.com/docs/guide.html 

Ref:Mongoose 之 Population 使用

Ref:http://mongoosejs.com/docs/2.7.x/index.html

{
    "name": "node-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "mongoose": "~3.6.13",
        "body-parser": "~1.0.1"
    }
}
package.json
// app/models/beacon.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var BeaconSchema       = new Schema({
    major        :Number,
    minor        :Number,
    range        :String//[I,N,F]
});

module.exports = mongoose.model('Beacon', BeaconSchema);
beacon.js
// app/models/catalog.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var CatalogSchema   = new Schema({
    tag            :String,
    name        :String,
    updateDate    :Date
});

module.exports = mongoose.model('Catalog', CatalogSchema);
catalog.js
// app/models/group.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var GroupSchema   = new Schema({
    tag            :String,
    name        :String,
    updateDate    :Date,
    things        :[{ type: Schema.Types.ObjectId, ref: 'Things' }]
});

module.exports = mongoose.model('Group', GroupSchema);
group.js
// app/models/post.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var PostSchema    = new Schema({
    title        :String,
    description    :String,
    html        :String,
    photo        :[String],
    audio        :[String],
    video        :[String],
    updateBy    :{ type: Schema.Types.ObjectId, ref: 'User' },
    updateDate    :Date,
    things        :{ type: Schema.Types.ObjectId, ref: 'Things' }
});

module.exports = mongoose.model('Post', PostSchema);
post.js
// app/models/things.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var BeaconSchema       = new Schema({
    major        :Number,
    minor        :Number,
    range        :String//[I,N,F]
});

var CommentSchema    = new Schema({
    text        :String,
    html        :String,
    photo        :String,
    audio        :String,
    video        :String,
    doodle        :String,
    type         :String,//[T,H,P,A,V,D]
    createBy    :{ type: Schema.Types.ObjectId, ref: 'User' },
    createDate    :Date
});

var ThingsSchema       = new Schema({
    catalog        :{ type: Schema.Types.ObjectId, ref: 'Catalog' },
    name        :String,
    photo        :String,
    description    :String,
    contactInfo    :String,
    type         :String,
    subType        :String,
    keyWord        :[String],
    owner        :{ type: Schema.Types.ObjectId, ref: 'User' },
    createDate    :Date,
    audioInfo    :[String],
    beacons        :[BeaconSchema],
    comments    :[CommentSchema]
});


module.exports = mongoose.model('Things', ThingsSchema);
things.js
// app/models/type.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var TypeSchema     = new Schema({
    tag     :String,
    name    :String,
    subType    :[TypeSchema]
});

module.exports = mongoose.model('Type', TypeSchema);
type.js
// app/models/user.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var UserSchema   = new Schema({
    firstname    :String,
    lastname    :String,
    nickname    :String,
    password    :String,
    gender        :String,//[F,M]
    email        :String,
    photo        :String,//base64
    wechat        :{},
    facebook    :{}
});

module.exports = mongoose.model('User', UserSchema);
user.js
// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

var mongoose   = require('mongoose');
mongoose.connect('mongodb://192.168.0.202:27017/webuzz'); // connect to our database

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 2397;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working (accessed at GET http://localhost:2397/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// model schema
// -------------------------------------------------
var User          = require('./app/models/user');
var Catalog      = require('./app/models/catalog');
var Beacon       = require('./app/models/beacon');
var Post      = require('./app/models/post');
var Things       = require('./app/models/things'); 
var Group        = require('./app/models/group'); 
var Type        = require('./app/models/type'); 
// -------------------------------------------------

// more routes for our API will happen here
// on routes that end in /users
// ----------------------------------------------------
router.route('/users')

    // create a user (accessed at POST http://localhost:2397/api/users)
    .post(function(req, res) {
        
        var user = new User();      // create a new instance of the User model
        user.nickname     = req.body.nickname;  // set the user info (comes from the request)
        user.firstname     = req.body.firstname; 
        user.lastname     = req.body.lastname; 
        user.password   = req.body.password;
        user.gender     = req.body.gender; 
        user.email         = req.body.email; 
        user.photo      = req.body.photo;
        user.wechat     = req.body.wechat; 
        user.facebook     = req.body.facebook; 

        // save the user and check for errors
        user.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'User created!' });
        });
        
    })

    // get all the users (accessed at GET http://localhost:2397/api/users)
    .get(function(req, res) {
        User.find(function(err, users) {
            if (err)
                res.send(err);

            res.json(users);
        });
    });

//find by email
router.route('/users/login/:email')
    .get(function(req, res) {
        User.find({'email':req.params.email}, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    });

//find by email & password
router.route('/users/login/:email/:password')
    .get(function(req, res) {
        User.findOne({
            'email'     : req.params.email,
            'password'  : req.params.password
            }, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    });

//find by facebook
router.route('/users/facebook/:id')
    .get(function(req, res) {
        User.findOne({'facebook.id':req.params.id}, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    });

//find by wechat
router.route('/users/wechat/:id')
    .get(function(req, res) {
        User.findOne({'wechat.id':req.params.id}, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    });

// on routes that end in /users/:id
// ----------------------------------------------------
router.route('/users/:id')

    // get the user with that id (accessed at GET http://localhost:2397/api/users/:id)
    .get(function(req, res) {
        User.findById(req.params.id, function(err, user) {
            if (err)
                res.send(err);
            res.json(user);
        });
    })

    // update the user with this id (accessed at PUT http://localhost:2397/api/users/:id)
    .put(function(req, res) {

        // use our user model to find the user we want
        User.findById(req.params.id, function(err, user) {

            if (err)
                res.send(err);

            user.nickname   = req.body.nickname;  // update the user info
            user.firstname     = req.body.firstname; 
            user.lastname     = req.body.lastname; 
            user.password   = req.body.password;
            user.gender     = req.body.gender; 
            user.email      = req.body.email; 
            user.photo      = req.body.photo;
            user.wechat     = req.body.wechat; 
            user.facebook     = req.body.facebook; 

            // save the user
            user.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'User updated!' });
            });

        });
    })

    // delete the user with this id (accessed at DELETE http://localhost:2397/api/users/:id)
    .delete(function(req, res) {
        User.remove({
            _id: req.params.id
        }, function(err, user) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

router.route('/catalogs')
    // create a catalog (accessed at POST http://localhost:2397/api/catalogs)
    .post(function(req, res) {
        
        var catalog         = new Catalog(); 
        catalog.tag         = req.body.tag;  
        catalog.name         = req.body.name; 
        catalog.updateDate     = req.body.updateDate; 

        catalog.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Catalog created!' });
        });
        
    })

    // get all the catalogs (accessed at GET http://localhost:2397/api/catalogs)
    .get(function(req, res) {
        Catalog.find(function(err, catalogs) {
            if (err)
                res.send(err);

            res.json(catalogs);
        });
    });

router.route('/catalogs/:id')
    .get(function(req, res) {
        Catalog.findById(req.params.id, function(err, catalog) {
            if (err)
                res.send(err);
            res.json(catalog);
        });
    })

    .put(function(req, res) {
        Catalog.findById(req.params.id, function(err, catalog) {

            if (err)
                res.send(err);

            catalog.tag         = req.body.tag;  
            catalog.name         = req.body.name; 
            catalog.updateDate     = req.body.updateDate; 
            
            catalog.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Catalog updated!' });
            });

        });
    })

    .delete(function(req, res) {
        Catalog.remove({
            _id: req.params.id
        }, function(err, catalog) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });
    
router.route('/things/addcomment/:id')
    .post(function(req, res) {
        Things.findById(req.params.id,function(err, things) {
            if (err)
                res.send(err);

            things.comments.push({
                "text"   : req.body.text,
                "html"   : req.body.html,
                "photo"  : req.body.photo,
                "audio"  : req.body.audio,
                "video"  : req.body.video,
                "doodle" : req.body.doodle,
                "type"   : req.body.type,
                "createBy"   : req.body.createBy,
                "createDate" : new Date(),
            });

            Things.update({_id:things._id},{ $set: {comments: things.comments} },function(err){
            if (err)
                res.send(err);
            });

            res.json({ message: 'Comments update!' });
        });
    });

router.route('/things')
    // create a things (accessed at POST http://localhost:2397/api/things)
    .post(function(req, res) {
        
        var things             = new Things(); 
        things.catalog         = req.body.catalog;  
        things.name         = req.body.name; 
        things.photo         = req.body.photo; 
        things.description  = req.body.description;
        things.contactInfo  = req.body.contactInfo;
        things.type         = req.body.type;
        things.subType      = req.body.subType;
        things.keyWord      = req.body.keyWord;
        things.owner         = req.body.owner;
        things.createDate   = req.body.createDate;
        things.audioInfo    = req.body.audioInfo;
        things.beacons        = req.body.beacons; 
        things.comments        = req.body.comments; 

        things.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Things created!' });
        });
        
    })

    // get all the things (accessed at GET http://localhost:2397/api/things)
    .get(function(req, res) {
        /*
        Things.find(function(err, things) {
            if (err)
                res.send(err);

            res.json(things);
        });*/

        Things.find()
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    });

router.route('/things/:id')
/*
    .get(function(req, res) {
        Things.findById(req.params.id, function(err, things) {
            if (err)
                res.send(err);
            res.json(things);
        });
    })*/


    .get(function(req, res) {
        Things.findById(req.params.id)
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    })

    .put(function(req, res) {
        Things.findById(req.params.id, function(err, things) {

            if (err)
                res.send(err);

            things.catalog      = req.body.catalog;  
            things.name         = req.body.name; 
            things.photo        = req.body.photo; 
            things.description  = req.body.description;
            things.contactInfo  = req.body.contactInfo;
            things.type         = req.body.type;
            things.subType      = req.body.subType;
            things.keyWord      = req.body.keyWord;
            things.owner        = req.body.owner;
            things.createDate   = req.body.createDate;
            things.audioInfo    = req.body.audioInfo;
            things.beacons      = req.body.beacons; 
            things.comments     = req.body.comments; 
            
            things.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Things updated!' });
            });

        });
    })

    .delete(function(req, res) {
        Things.remove({
            _id: req.params.id
        }, function(err, things) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

//filter catalog
router.route('/things/catalog/:id')
    .get(function(req, res) {
        Things.find({'catalog':req.params.id})
             /*
              .populate({
                path  : 'catalog',
                match : {tag : req.params.tag}
              })*/
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    });

//filter owner
router.route('/things/owner/:id')
    .get(function(req, res) {
        Things.find({
            'owner':req.params.id
            })
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    });

//filter type
router.route('/things/type/:type')
    .get(function(req, res) {
        Things.find({
            'type':req.params.type
            })
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    });

//filter type & sub type
router.route('/things/type/:type/:subType')
    .get(function(req, res) {
        Things.find({
            'type':req.params.type,
            'subType':req.params.subType
            })
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    });

//filter key words
router.route('/things/keyword/:key')
    .get(function(req, res) {
        Things.find({
            'keyWord':{"$in":[req.params.key]}
            })
              .populate('catalog')
              .populate('owner')
              .populate('comments.createBy')
              .exec(function(err,things){
            if (err)
                res.send(err);
            res.json(things);
        }); 
    });

router.route('/posts')
    // create a posts (accessed at POST http://localhost:2397/api/posts)
    .post(function(req, res) {

        var posts             = new Post(); 
        posts.title         = req.body.title;  
        posts.description     = req.body.description; 
        posts.html          = req.body.html; 
        posts.photo         = req.body.photo;
        posts.audio         = req.body.audio; 
        posts.video         = req.body.video;     
        posts.updateBy        = req.body.updateBy; 
        posts.updateDate    = req.body.updateDate; 
        posts.things         = req.body.things;

        posts.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Post created!' });
        });
        
    })

    // get all the posts (accessed at GET http://localhost:2397/api/posts)
    .get(function(req, res) {
        Post.find(function(err, posts) {
            if (err)
                res.send(err);

            res.json(posts);
        });
    });

router.route('/posts/:id')
    .get(function(req, res) {
        Post.findById(req.params.id, function(err, posts) {
            if (err)
                res.send(err);
            res.json(posts);
        });
    })

    .put(function(req, res) {
        Post.findById(req.params.id, function(err, posts) {

            if (err)
                res.send(err);

            posts.title         = req.body.title;  
            posts.description   = req.body.description; 
            posts.html          = req.body.html; 
            posts.photo         = req.body.photo;
            posts.audio         = req.body.audio; 
            posts.video         = req.body.video;   
            posts.updateBy      = req.body.updateBy; 
            posts.updateDate    = req.body.updateDate; 
            posts.things        = req.body.things;
            
            posts.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Post updated!' });
            });

        });
    })

    .delete(function(req, res) {
        Post.remove({
            _id: req.params.id
        }, function(err, posts) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

router.route('/types')
    // create a types (accessed at POST http://localhost:2397/api/types)
    .post(function(req, res) {

        var types   = new Type(); 
        types.tag   = req.body.tag;
        types.name   = req.body.name;  
        types.subType  = req.body.subType; 

        types.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Type created!' });
        });
        
    })

    // get all the types (accessed at GET http://localhost:2397/api/types)
    .get(function(req, res) {
        Type.find(function(err, types) {
            if (err)
                res.send(err);

            res.json(types);
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Mongo Server running on port ' + port);
server.js

Ref:N-blog 使用 Express + MongoDB 搭建多人博客

Ref:Mongodb Aggregation

Ref:Mongodb Mapreduce 初窥

Ref:Hadoop学习笔记:MapReduce框架详解

Ref:Hadoop学习笔记系列文章导航

(1)王路情,《Hadoop之MapReduce》:http://blog.csdn.net/wangloveall/article/details/21407531

(2)Suddenly,《Hadoop日记之MapReduce》:http://www.cnblogs.com/sunddenly/p/3985386.html

(3)伯乐在线,《我是如何向老婆解释MapReduce的》:http://blog.jobbole.com/1321/

(4)codingwu,《MapReduce原理与设计思想》:http://www.cnblogs.com/archimedes/p/mapreduce-principle.html

(5)codingwu,《MapReduce实例浅析》:http://www.cnblogs.com/archimedes/p/mapreduce-example-analysis.html

(6)挑灯看剑,《图解MapReduce原理和执行过程》:http://blog.csdn.net/michael_kong_nju/article/details/23826979

(7)万川梅、谢正兰,《Hadoop应用开发实战详解(修订版)》:http://item.jd.com/11508248.html

(8)张月,《Hadoop MapReduce开发最佳实践》:http://www.infoq.com/cn/articles/MapReduce-Best-Practice-1

posted @ 2016-03-04 00:28  Nick.Chung  阅读(710)  评论(0编辑  收藏  举报