nodejs+express+mongo 實際一套增刪改查的接口

nodejs+mongoose+express 實現數據的增刪改查

定義數據模型

//bear.js
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var BearSchema=new Schema({
    name:String
});
module.exports=mongoose.model('Bear',BearSchema);

package.json

{
    "name":"node-mongo-express",
    "version":"1.0.0",
    "description":"實現數據的增刪改查",
    "main":"server.js",
    "license":"MIT",
    "dependencies":{
        "express":"~4.0.0",
        "mongoose":"~3.6.13",
        "body-parser":"~1.0.1"
    }
}

實例代碼

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp')
app.use(bodyParser.urlencoded({ extended: true }));
var Bear = require('./app/models/bear');
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function (req, res, next) {//增長
    console.log('觸發中間件.');
    next();
});
router.route('/bears').post(function (req, res) {//post請求來增長一條數據
    var bear = new Bear();
    bear.name = req.body.name;
    bear.save(function (err) {
        if (err)
            res.send(err);
        res.json({ message: 'Bear created!' });
    });
})
router.route('/bears/:bear_id')
.get(function (req, res) {//根據id來查找對應的數據
    console.log(req.params.bear_id);
    Bear.findById(req.params.bear_id, function (err, bear) {
        if (err)
            res.send(err);
        res.json(bear);
    });
})
.put(function (req, res) {//經過put請求來更新數據
    Bear.findById(req.params.bear_id, function (err, bear) {
        if (err)
            res.send(err);
        bear.name = req.body.name;
        bear.save(function (err) {
            if (err)
                res.send(err);
            res.json({ message: 'Bear updated!' });
        });
    });
})
.delete(function (req, res) {//刪除數據
    Bear.remove({
        _id: req.params.bear_id
    }, function (err, bear) {
        if (err)
            res.send(err);
        res.json({ message: 'Successfully deleted' });
    })
})
router.get('/', function (req, res) {//訪問首頁
    res.json({ message: 'hooray!welcome to our api!' });
});
app.use('/api', router);


app.listen(port);
console.log("Magic happens on port " + port);
相關文章
相關標籤/搜索