添加mongoose

  1. mkdir models
  2. npm i -S mongoose
  3. npm i -S mongoosedao

在路由里增加创建代码

配置

配置mongodb链接信息

  • config/mongodb.example.js
  • db.js
  1. cp config/mongodb.example.js config/mongodb.js

创建models/user.js

  1. var mongoose = require('mongoose');
  2. var Schema = mongoose.Schema;
  3. var MongooseDao = require('mongoosedao');
  4. var userSchema = new Schema(
  5. {
  6. "name":"String",
  7. "password":"String"
  8. }
  9. );
  10. var User = mongoose.model('User', userSchema);
  11. <!-- var UserDao = new MongooseDao(User); -->
  12. module.exports = User;

测试user.js

  1. import test from 'ava'
  2. import superkoa from 'superkoa'
  3. // 1、引入`mongoose connect`
  4. require('../db');
  5. // 2、引入`User` Model
  6. const User = require('../models/user');
  7. // 3、定义`user` Entity
  8. let user = new User({
  9. username: 'i5ting',
  10. password: '0123456789'
  11. });
  12. test.cb('#save()', t => {
  13. user.save((err, u) => {
  14. if (err) log(err)
  15. t.is(u.username, 'i5ting');
  16. t.end()
  17. });
  18. });

在测试完成后需要在after里删除测试数据,保证测试完整性,自己写吧

在路由里增加user创建和api测试

routes/users.js

  1. var User = require('../models/user')
  2. var router = require('koa-router')();
  3. router.get('/', function (ctx, next) {
  4. ctx.body = 'this a users response!';
  5. });
  6. router.post('/register2', function(ctx, next) {
  7. var name = ctx.request.body.username;
  8. var password = ctx.request.body.password;
  9. var u = new User({
  10. "username":name,
  11. "password":password
  12. })
  13. console.log(u)
  14. return u.save(function (err, user) {
  15. console.log(err)
  16. console.log(user)
  17. if (err) {
  18. return ctx.body = {'info': 'register failed with err'};
  19. }
  20. return ctx.body = {'info': 'register sucess'};
  21. });
  22. });
  23. module.exports = router;

test/user_api.js

  1. import test from 'ava'
  2. import superkoa from 'superkoa'
  3. var req = superkoa(require('path').resolve(__dirname, '../app'))
  4. test.cb("POST /users/register", t => {
  5. req
  6. .post('/users/register2')
  7. .field('username', 'stuq')
  8. .field('password', '123456')
  9. .set('Accept', 'application/json')
  10. .expect('Content-Type', /json/)
  11. .expect(200, function (err, res) {
  12. t.ifError(err)
  13. t.is(res.body.info, 'register sucess', 'res.text == Hello Koa')
  14. t.end()
  15. });
  16. });

测试

  1. ava -v test/user_api.js