nodejs+express+mongo 实际一套增删改查的接口

杀马特。学长 韩版系。学妹 提交于 2020-04-07 02:12:26

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!