基于express 的mongoose基本应用
1.封装一个dao 层,连接mongodb
var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost:27017/db1'); //连接db1数据库 var Schema = mongoose.Schema; //创建模型 var listSchema = new Schema({ text: String, href: String }); var list = mongoose.model('lists', listSchema); //exports.student=student; module.exports = list;
2.在Service 层即index.js 分配路由地址
var express = require('express'); var router = express.Router(); var cheerio = require('cheerio'); var superagent = require('superagent'); var list = require('../database/mongodb'); router.get('/', function (req, res, next) { res.render('index', { title: 'Index' }); }); //查询数据库 router.get('/index/list', function (req, res) { var lists = list.find(function (err, result) { if (err) { res.send(err) } else { res.json(result) } }) }); //利用爬虫抓取html结构 router.get('/index/getCnblogs', function (req, res, next) { //res.header("Access-Control-Allow-Origin", "*"); superagent.get('https://news.cnblogs.com/').end(function (err, sres) { if (err) { return next(err) } var $ = cheerio.load(sres.text); var items = []; $(".news_entry a").each(function (index, ele) { var element = $(ele); items.push({ text: element.text(), href: element.attr('href') }) }); //将抓取到的数据存到数据库中 list.insertMany(items, function (rs) { res.json({ success: true }) }) }) }); //增加一条数据到mongoose router.post('/index/addList', function (req, res, next) { var item = req.body; list.create(item, function (re) { res.json({ success: true }) }) }); module.exports = router;
后记:从前端的角度来讲,更注重于用户体验,关心于用户的请求,及请求后所有可能发生的状态并做处理。如果不清楚后端逻辑实现,就无法在与后端对接时了解自己究竟想要的数据模型和可能结果