node增删改查

var express = require('express');
var router = express.Router();
var models = require('../models') // 引入模板
var Op = models.Sequelize.Op

// 查询所有
router.get('/', async function (req, res, next) {
    // 搜索
    var where = {}
    var title = req.query.title;
    var content = req.query.content;
    console.log(req.query);
    
    if (title) {
        where = {
           [Op.or]:[{ // 模糊搜索,一个关键字,搜索两个字段
               title:{[Op.like]: '%' + title + '%'}
           },
           {
              content:{[Op.like]: '%' + title + '%'}
        }]
        }
    }
    var articles  = await models.Article.findAll({
        order:[['id','DESC']],
        where:where
    })
    res.json({articles: articles})
});

// 新增
router.post('/', async function(req,res,next){
    //console.log(req.body.title);
   await models.Article.create(req.body)// create创造

   var articles  = await models.Article.findAll({ // 返回所有数据
    order:[['id','DESC']]
})
    res.json({success:'新增成功',artcles:articles})
})

// 查询单条
router.get('/:id',async function(req,res,next){
    var article = await models.Article.findByPk(req.params.id);
    res.json({article: article});
})

//  修改
router.put('/:id',async function(req,res,next){
    var article = await models.Article.findByPk(req.params.id);
    article.update(req.body)
    console.log(req.body);
    res.json({success:'修改成功',article:article})
})

//  删除
router.delete('/:id',async function(req,res,next){
    var article = await models.Article.findByPk(req.params.id);
    article.destroy();
    res.json({success:'删除成功'})
})

// 模糊搜索

module.exports = router;

 

posted @ 2020-06-08 15:38  飞鸟和蝉-  阅读(540)  评论(0编辑  收藏  举报