express + mongodb RESTful API

确保已经安装了node

初始化node工程

mkdirn restful-api && cd restful-api
npm init //配置随便写

添加依赖

npm install --save express
npm install --save mongoose

数据结构stockModel

// stockModel.js
var mongoose = require('mongoose');
// Setup schema
var stockSchema = mongoose.Schema({
    company_name: {
        type: String,
        required: true
    },
    ticker: {
        type: String,
        required: true
    },
    url: {
        type: String,
        required: true
    },
    open_price: {
        type: String,
        required: true
    },
    open_date: {
        type: String,
        required: true
    },
    close_price: {
        type: String,
        required: true
    },
    close_date: {
        type: String,
        required: true
    }
},{
    strict: false // false表示结构可变
});
// Export stock model
var stock = module.exports = mongoose.model('stocks', stockSchema);
module.exports.get = function (callback, limit) {
    stock.find(callback).limit(limit);
}

操作stockModel的controller

// stockController.js
// Import stock model
Stock = require('./stockModel');
// Handle index actions
exports.index = function (req, res) {
    Stock.get(function (err, stocks) {
        if (err) {
            res.json({
                status: "error",
                message: err,
            });
        }
        res.json({
            status: "success",
            message: "stocks retrieved successfully",
            data: stocks
        });
    });
};
// Handle create stock actions
exports.new = function (req, res) {
    var stock = new Stock();
    stock.name = req.body.name ? req.body.name : stock.name;
    stock.gender = req.body.gender;
    stock.email = req.body.email;
    stock.phone = req.body.phone;
// save the stock and check for errors
    stock.save(function (err) {
        // if (err)
        //     res.json(err);
res.json({
            message: 'New stock created!',
            data: stock
        });
    });
};
// Handle view stock info
exports.view = function (req, res) {
    Stock.findById(req.params.stock_id, function (err, stock) {
        if (err)
            res.send(err);
        res.json({
            message: 'stock details loading..',
            data: stock
        });
    });
};
// Handle update stock info
exports.update = function (req, res) {
Stock.findById(req.params.stock_id, function (err, stock) {
        if (err)
            res.send(err);
stock.name = req.body.name ? req.body.name : stock.name;
        stock.gender = req.body.gender;
        stock.email = req.body.email;
        stock.phone = req.body.phone;
// save the stock and check for errors
        stock.save(function (err) {
            if (err)
                res.json(err);
            res.json({
                message: 'stock Info updated',
                data: stock
            });
        });
    });
};
// Handle delete stock
exports.delete = function (req, res) {
    Stock.remove({
        _id: req.params.stock_id
    }, function (err, stock) {
        if (err)
            res.send(err);
res.json({
            status: "success",
            message: 'stock deleted'
        });
    });
};

设置路由

// api-routes.js
// Initialize express router
let router = require('express').Router();
// Set default API response
router.get('/', function (req, res) {
    res.json({
        status: 'API Its Working',
        message: 'Welcome to RESTHub crafted with love!',
    });
});
// Import stock controller
var stockController = require('./stockController');
// stock routes
router.route('/stocks')
    .get(stockController.index)
    .post(stockController.new);
router.route('/stocks/:stock_id')
    .get(stockController.view)
    .patch(stockController.update)
    .put(stockController.update)
    .delete(stockController.delete);
// Export API routes
module.exports = router;

服务器逻辑

// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialise the app
let app = express();

// Import routes
let apiRoutes = require("./api-routes");
// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
// Connect to Mongoose and set connection variable
mongoose.connect('mongodb://localhost:27107/resthub', { useNewUrlParser: true});
var db = mongoose.connection;

// Added check for DB connection
if(!db)
    console.log("Error connecting db")
else
    console.log("Db connected successfully")

// Setup server port
var port = process.env.PORT || 8080;

// Send message for default URL
app.get('/', (req, res) => res.send('Hello World with Express'));

// Use Api routes in the App
app.use('/api', apiRoutes);
// Launch app to listen to specified port
app.listen(port, function () {
    console.log("Running RestHub on port " + port);
});

启动

node index.js //也可以安装热启动nodemon nodemon index.js
成功启动

以数据爬取的数据作为数据源

请求结果

你可能感兴趣的:(express + mongodb RESTful API)