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主主(读写分离)集群建立+代码包+持续上线+备份)
一.前言 最近公司做了一套新产品,需要发布到不确定的硬件环境中(不同使用单位规模,使用人数,服务器提供的资源不同)若每次进行人工部署耗时费力,周期过长. 二.分析 具体的部署流程如下: 由上图流程进行 ...
随机推荐
- linux 后台运行命令
command & 关闭终端,程序会终止 nohup command & 关闭终端,程序不会终止
- oracle授予调用存储过程权限
参考 https://blog.csdn.net/h254532693/article/details/45364317 grant execute on PROCEDURENAME to USERN ...
- Python设计模式 - 总览(更新中...)
最近打算重构部分python项目,有道是"工欲善其事,必先利其器",所以有必要梳理一下相关设计模式.每次回顾基本概念或底层实现时都会有一些新的收获,希望这次也不例外. 本系列打算先 ...
- rancher 2 webhook 格式
{ "version":"4", "groupKey":<string>, "status":"& ...
- node搭建简单的本地服务器
首先要安装node,方法很多,可以去网上找找,可以直接去官网下载安装,新版本的node是自带npm的: 安装好以后,新建一个js文件,名为server.js: let http = require(' ...
- tf.layers.dense()
tf.layers.dense用法 2018年05月30日 19:09:58 o0haidee0o 阅读数:20426 dense:全连接层 相当于添加一个层,即初学的add_layer()函数 ...
- wiper
wiper - 必应词典 美['waɪpər]英['waɪpə(r)] n.手绢儿:搌布:揩布:(汽车风挡上的)雨刷器 网络刮水器:雨刮器:拭雨器 变形复数:wipers:
- 20 【python】入门指南:常用数据结构
Python内置了三种高级数据结构:list,tuple,dict list:数组,相同类型的元素组成的数组 tuple:元组,相同类型的元素组成的数组,但是这里有限定条件(长度是固定的,并且值也是固 ...
- VS项目属性配置问题
1 libcpmtd.lib(stdthrow.obj) : error LNK2001: 无法解析的外部符号 __CrtDbgReportW 运行库:多线程 (/MT) 2 MSVCRT.lib( ...
- Bootstrap(3) 表格与按钮
1.表格 基本格式,实现基本的表格样式 <table class="table"> <thead> <tr> <th>编号</ ...