zoukankan      html  css  js  c++  java
  • Nodejs+Mongo+WebAPI

    Nodejs+Mongo+WebAPI集成

    1.【 目录】:

    |- models/bear.js

    |- node_modules/

            |- express

            |- mongoose

            |- body-parser

    |- Server.js

    |- package.json

    2. 【代码】:

    //Server.js

      1 // server.js
      2 
      3 // base setup
      4 // ===========================================================
      5 
      6 // call the package we need
      7 var express     = require('express');    // call expreess
      8 var app            = express();            // define our app using express
      9 var bodyParser    = require('body-parser');
     10 
     11 // mongoose setup
     12 var mongoose    = require('mongoose');
     13 mongoose.connect('mongodb://localhost:27017/myDatabase')    // connect to database 'myDatabase'
     14 
     15 // models setup
     16 var Bear = require('./models/bear')
     17 
     18 // configure app to use bodyParser()
     19 // this will let us get the data from a POST
     20 app.use( bodyParser.urlencoded({ extended: true}));
     21 app.use( bodyParser.json());
     22 
     23 var port = process.env.PORT || 3000;
     24 
     25 
     26 
     27 // routes for our API
     28 // ==============================================================
     29 var router = express.Router();
     30 
     31 
     32 // 1. middle ware 
     33 router.use( function(req, res, next){
     34     // do logging
     35     console.log('Something is happening.');
     36     next();
     37 });
     38 
     39 // 2. test route to make sure everything is work 
     40 router.get('/', function(req, res){
     41     res.json( { message: 'Horray! Welcome to our api!'});
     42 });
     43 
     44 // 3. routes end in: /bears
     45 router.route('/bears')
     46 
     47     // 3-1. create a bear (accessed at POST http://localhost:3000/api/bears)
     48     .post( function(req, res){        
     49         var newBear = new Bear();        // create a new instance of the Bear model
     50         newBear.name = req.body.name;    // set the bears name ( comes from the request )
     51         
     52         // save the bear and check for errors
     53         newBear.save ( function(err){
     54             if(err)
     55                 res.send(err);
     56             res.json({ message: 'Bear created!'});            
     57          });
     58     })
     59     
     60     // 3-2. get all the bears (accessed at GET http://localhost:3000/api/bears)
     61     .get( function(req, res){
     62         Bear.find( function(err, bears){
     63             if(err)
     64                 res.send(err);
     65             res.json(bears);
     66         })
     67     } );  
     68 
     69 // 4. routes end in: /bears/:bears_id
     70 router.route('/bears/:bear_id')
     71 
     72     //4-1. get the bear with this id (accessed at GET http://localhost:3000/api/bears/:bear_id)
     73     .get(function(req, res){
     74         Bear.findById(req.params.bear_id, function(err, bear){
     75             if(err)
     76                 res.send(err);
     77             res.json(bear);
     78         });
     79     })
     80     
     81     // 4-2. update the bear with this id (accessed at PUT http://localhost:3000/api/bears/:bear_id)
     82     .put(function(req, res){
     83         
     84         // use bear model to find the bear we want
     85         Bear.findById(req.params.bear_id, function(err, bear){
     86             if(err)
     87                 res.send(err);
     88             bear.name = req.body.name; // update the bears info
     89             
     90             // save the bear
     91             bear.save(function(err){
     92                 if(err)
     93                     res.send(err);
     94                 res.json({message: 'Bear updated!'});
     95             });
     96         });
     97     })
     98     
     99     // 4-3. delete the bear with this id (accessed at DELETE http://localhost:3000/api/bears/:bear_id)
    100     .delete(function(req, res){
    101         Bear.remove(
    102             {
    103                 _id: req.params.bear_id
    104             }, function(err, bear){
    105                 if(err)
    106                     res.send(err);
    107                 res.json({ message: 'Successfully deleted!'});
    108             }
    109         )
    110     });
    111 
    112 // more routes for our API will happen here
    113 
    114 // REGISTER OUR ROUTES
    115 
    116 // all of our routes will be prefixed with /api
    117 app.use('/api', router);
    118 
    119 
    120 // start the server
    121 // ==============================================
    122 app.listen(port);
    123 console.log('Magic happens on port : ' + port);

    // models/bear.js

    1 var mongoose    = require('mongoose');
    2 var Schema        = mongoose.Schema;
    3 
    4 var BearSchema    = new Schema( {
    5     name:    String
    6 });
    7 
    8 module.exports = mongoose.model('Bear', BearSchema);
  • 相关阅读:
    关于JavaWeb项目汉字乱码问题
    使用pipenv
    python使用imap-tools模块下载邮件中的附件
    Python新增功能, 函数的参数类型提示.
    centos83+django3.1+ASGI+nginx部署.
    python3.9 pip本身的升级
    windows+django3.1+ASGI+nginx部署
    k8s 单节点开发环境用hostPath配置mysql的持久化存储
    Rust的设计中为什么要区分不可变变量和常量?
    Vscode + Python + Django开发环境常见问题
  • 原文地址:https://www.cnblogs.com/dzone/p/4979481.html
Copyright © 2011-2022 走看看