1 AccountModel.js
const mongoose = require('mongoose');
let AccountSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
time: Date,
type: {
type: Number,
default: -1
},
account: {
type: Number,
required: true
},
remarks: {
type: String
}
});
let AccountModel = mongoose.model('accounts', AccountSchema);
module.exports = AccountModel;
2 app.js
const accountRouter = require('./routes/api/account');
3 account.js
var express = require('express');
var router = express.Router();
const moment = require('moment');
const AccountModel = require('../../models/AccountModel');
router.get('/account', function(req, res, next) {
AccountModel.find().sort({time: -1}).exec((err, data) => {
if(err){
res.json({
code: '1001',
msg: '读取失败~~',
data: null
})
return;
}
res.json({
code: '0000',
msg: '读取成功',
data: data
});
})
});
router.post('/account', (req, res) => {
AccountModel.create({
...req.body,
time: moment(req.body.time).toDate()
}, (err, data) => {
if(err){
res.json({
code: '1002',
msg: '创建失败~~',
data: null
})
return
}
res.json({
code: '0000',
msg: '创建成功',
data: data
})
})
});
router.delete('/account/:id', (req, res) => {
let id = req.params.id;
AccountModel.deleteOne({_id: id}, (err, data) => {
if(err) {
res.json({
code: '1003',
msg: '删除账单失败',
data: null
})
return;
}
res.json({
code: '0000',
msg: '删除成功',
data: {}
})
})
});
router.get('/account/:id', (req, res) => {
let {id} = req.params;
AccountModel.findById(id, (err, data) => {
if(err){
return res.json({
code: '1004',
msg: '读取失败~~',
data: null
})
}
res.json({
code: '0000',
msg: '读取成功',
data: data
})
})
});
router.patch('/account/:id', (req, res) => {
let {id} = req.params;
AccountModel.updateOne({_id: id}, req.body, (err, data) => {
if(err){
return res.json({
code: '1005',
msg: '更新失败~~',
data: null
})
}
AccountModel.findById(id, (err, data) => {
if(err){
return res.json({
code: '1004',
msg: '读取失败~~',
data: null
})
}
res.json({
code: '0000',
msg: '更新成功',
data: data
})
})
});
});
module.exports = router;