上节我们使用mongoose实现了数据库调用,此次我们进行api使用的学习。
使用方法很简单,只需要修改routers下index文件下的代码即可。
以新增数据为例,原代码:
- router.post('/account', function(req, res, next) {
- // console.log(req.body);
- //插入数据库
- accountModel.create({...req.body,time:moment(req.body.time).toDate()}).then((data,err)=>{
- if(err){
- res.status(500).send('插入失败')
- return
- }
- let account=accountModel.find().sort({time:-1}).then((data1,err)=>{
- console.log(data1);
- res.render('account', { account:data1 ,moment:moment});
- });
-
- })
-
- });
只需要修改响应成功部分,返回json数据即可,如下
- router.post('/account', function(req, res, next) {
- // console.log(req.body);
- //插入数据库
- accountModel.create({
- ...req.body,
- time: moment(req.body.time).toDate()
- }).then((data, err) => {
- if (err) {
- res.json({
- code: '1001',
- msg: '读取失败',
- data: null
- })
- return
- }
- console.log(data);
- res.json({
- code: '20000',
- msg: '读取成功',
- data: data
- })
- })
-
- });
可以通过postman软件查看接口情况
