Nodejs+Mongo+WebAPI
Nodejs+Mongo+WebAPI集成
1.【 目录】:
|- models/bear.js
|- node_modules/
|- express
|- mongoose
|- body-parser
|- Server.js
|- package.json
2. 【代码】:
//Server.js
// server.js // base setup
// =========================================================== // call the package we need
var express = require('express'); // call expreess
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // mongoose setup
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myDatabase') // connect to database 'myDatabase' // models setup
var Bear = require('./models/bear') // 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 || ; // routes for our API
// ==============================================================
var router = express.Router(); // 1. middle ware
router.use( function(req, res, next){
// do logging
console.log('Something is happening.');
next();
}); // 2. test route to make sure everything is work
router.get('/', function(req, res){
res.json( { message: 'Horray! Welcome to our api!'});
}); // 3. routes end in: /bears
router.route('/bears') // 3-1. create a bear (accessed at POST http://localhost:3000/api/bears)
.post( function(req, res){
var newBear = new Bear(); // create a new instance of the Bear model
newBear.name = req.body.name; // set the bears name ( comes from the request ) // save the bear and check for errors
newBear.save ( function(err){
if(err)
res.send(err);
res.json({ message: 'Bear created!'});
});
}) // 3-2. get all the bears (accessed at GET http://localhost:3000/api/bears)
.get( function(req, res){
Bear.find( function(err, bears){
if(err)
res.send(err);
res.json(bears);
})
} ); // 4. routes end in: /bears/:bears_id
router.route('/bears/:bear_id') //4-1. get the bear with this id (accessed at GET http://localhost:3000/api/bears/:bear_id)
.get(function(req, res){
Bear.findById(req.params.bear_id, function(err, bear){
if(err)
res.send(err);
res.json(bear);
});
}) // 4-2. update the bear with this id (accessed at PUT http://localhost:3000/api/bears/:bear_id)
.put(function(req, res){ // use bear model to find the bear we want
Bear.findById(req.params.bear_id, function(err, bear){
if(err)
res.send(err);
bear.name = req.body.name; // update the bears info // save the bear
bear.save(function(err){
if(err)
res.send(err);
res.json({message: 'Bear updated!'});
});
});
}) // 4-3. delete the bear with this id (accessed at DELETE http://localhost:3000/api/bears/:bear_id)
.delete(function(req, res){
Bear.remove(
{
_id: req.params.bear_id
}, function(err, bear){
if(err)
res.send(err);
res.json({ message: 'Successfully deleted!'});
}
)
}); // more routes for our API will happen here // REGISTER OUR ROUTES // all of our routes will be prefixed with /api
app.use('/api', router); // start the server
// ==============================================
app.listen(port);
console.log('Magic happens on port : ' + port);
// models/bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema( {
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
Nodejs+Mongo+WebAPI的更多相关文章
- nodejs+mongo 实现搜附近的人
参考网址:http://blog.csdn.net/huangrunqing/article/details/9112227 用mongo作为存储,来实现搜索附近的人具有先天的优势, MongoDB原 ...
- 【开源】NodeJS仿WebApi路由
用过WebApi或Asp.net MVC的都知道微软的路由设计得非常好,十分方便,也十分灵活.虽然个人看来是有的太灵活了,team内的不同开发很容易使用不同的路由方式而显得有点混乱. 不过这不是重点, ...
- NodeJS仿WebApi路由
用过WebApi或Asp.net MVC的都知道微软的路由设计得非常好,十分方便,也十分灵活.虽然个人看来是有的太灵活了,team内的不同开发很容易使用不同的路由方式而显得有点混乱. 不过这不是重点, ...
- nodejs&mongo&angularjs
http://www.ibm.com/developerworks/cn/web/wa-nodejs-polling-app/
- 十个最适合 Web 和 APP 开发的 NodeJS 框架
在浏览器以外运行 JavaScript 对于 JavaScript 爱好者来说非常神奇,同时也肯定是 web 应用程序开发界最受欢迎的进步之一.全球各地的开发者张开双臂拥抱 NodeJS. 对于新手来 ...
- mongo&node
///// node install $ sudo apt-get install python-software-properties $ curl -sL https://deb.nodesou ...
- 10 个最适合 Web 和 APP 开发的 NodeJS 框架
在浏览器以外运行 JavaScript 对于 JavaScript 爱好者来说非常神奇,同时也肯定是 web 应用程序开发界最受欢迎的进步之一.全球各地的开发者张开双臂拥抱 NodeJS. 对于新手来 ...
- node.js零基础详细教程(7.5):mongo可视化工具webstorm插件、nodejs自动重启模块Node Supervisor(修改nodejs后不用再手动命令行启动服务了)
第七章 建议学习时间4小时 课程共10章 学习方式:详细阅读,并手动实现相关代码 学习目标:此教程将教会大家 安装Node.搭建服务器.express.mysql.mongodb.编写后台业务逻辑. ...
- 一个适合变化的产品部署集成包(nginx+jdk+tomcat+nodejs+mysql+redis+mongo+MYSQL主主(读写分离)集群建立+代码包+持续上线+备份)
一.前言 最近公司做了一套新产品,需要发布到不确定的硬件环境中(不同使用单位规模,使用人数,服务器提供的资源不同)若每次进行人工部署耗时费力,周期过长. 二.分析 具体的部署流程如下: 由上图流程进行 ...
随机推荐
- :after伪类+content经典应用举例
:after伪类+content 清除浮动的影响 .box{padding:10px; background:gray;} .l{float:left;} <div class="bo ...
- sqoop2 缺少 jackson-core-asl-1.8.8.jar 和 jackson-mapper-asl-1.8.8.jar 这两个jar包
[root@spark2 client]# cat /var/log/sqoop2/localhost.2017-12-22.log 十二月 22, 2017 10:29:17 上午 org.apac ...
- word2vec详解与实战
有那么一句话 不懂word2vec,就别说自己是研究人工智能->机器学习->自然语言处理(NLP)->文本挖掘的 所以接下来我就从头至尾的详细讲解一下word2vec这个东西. 简要 ...
- 不要62(数位DP)
不要62 http://acm.hdu.edu.cn/showproblem.php?pid=2089 Time Limit: 1000/1000 MS (Java/Others) Memory ...
- Codeforces Beta Round #70 (Div. 2)
Codeforces Beta Round #70 (Div. 2) http://codeforces.com/contest/78 A #include<bits/stdc++.h> ...
- 问题2:css图片、文字居中
1. 文本或图片水平对齐:父元素中添加以下样式 text-align : center;2. 单行文字垂直对齐:父元素中添加以下样式 line-height : 父元素高度; 3.图片 ...
- AtCoder Regular Contest 092 C - 2D Plane 2N Points(二分图匹配)
Problem Statement On a two-dimensional plane, there are N red points and N blue points. The coordina ...
- [剑指Offer]24-反转链表
题目链接 https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&t ...
- f5冗余BIG-IP系统的安装
1.设备服务群集 •一个系列的BIG-Ips彼此互相支持DSC •每一台BIG-IP 自己生成一个Device Object •不同设备的信息 •建立信任证书 •在local device上设置Dev ...
- listView悬浮头部的简单实现
简而言之 为listView设置onScrollListener 当滑动时 firstVisibleItem>=要悬浮的 item的position时 让悬浮部分显示 否则隐藏 其实就是 ...