您的位置:首页 > 数据库 > Mongodb

RESTful Mongodb

2016-03-04 00:28 501 查看
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

// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: