koa-rest-mongoose, koa 1.x 与 Nodejs 结合使用
koa-rest-mongoose, koa 1.x 与 Nodejs 结合使用
why
期初我就是想找个能根据 model 生成 api 的库,找到了个叫 koa-mongo-rest 的,貌似很久没维护了,现在 koa-router 的版本低了,所以我照着他搞了一个。 如果你们需要的话。
koa-rest-mongoose
mongoose rest generator for koa
安装
Install using npm:
npm install koa-rest-mongoose
示例
var koa = require('koa');
var router = require('koa-router')();
var koaRestMongoose = require(‘koa-rest-mongoose’);
var mongoUrl = ‘127.0.0.1:27017/koa_rest_mongoose’;
var mongoose = require(‘mongoose’);
mongoose.connect(mongoUrl);
var schema = new mongoose.Schema({
email: String,
name: String,
password: String,
address: String,
zipcode: Number,
lists: Array
});
var model = mongoose.model(‘user’, schema);
var app = koa();
koaRestMongoose(app, router, model, ‘/api’);
app.listen(process.env.PORT || 5000);
Following REST API is now created for you:
| HTTP Verb | /users | /users/:id |
| ------------- | ------------- | --------------- |
| GET | Get all documents, or documents that match the query.
You can use [mongoose find conditions] ( http://mongoosejs.com/docs/queries.html), limit, skip and sort.
For example:
/api/users?conditions={"name":"john"}&limit=10&skip=1&sort=-zipcode | Get the addressed document. |
| POST | Create a new document and send it back. | Update the addressed document with specified attributes. |
| PUT | Create a new document and send it back. | Replace the addressed document. |
| DELETE | n/a | Delete the addressed document. |
| PATCH | n/a | Update the addressed document with specified attributes. |
测试
npm test
推荐
sequelize
最后
欢迎 issues 或者 pr :)
在使用 Koa 1.x 与 Node.js 结合构建 RESTful API 时,koa-rest-mongoose
是一个方便的中间件,可以帮助你快速地将 Mongoose 模型映射到 Koa 路由上。下面是一个简单的示例,展示如何配置和使用它们。
首先,确保你已经安装了必要的包:
npm install koa koa-router koa-bodyparser mongoose koa-rest-mongoose
然后,你可以按照以下步骤进行配置:
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const mongoose = require('mongoose');
const restMongoose = require('koa-rest-mongoose');
mongoose.connect('mongodb://localhost:27017/yourdb', { useNewUrlParser: true, useUnifiedTopology: true });
const app = new Koa();
const router = new Router();
// 假设你有一个 User 模型
const User = mongoose.model('User', new mongoose.Schema({ name: String }));
// 使用 koa-rest-mongoose 中间件
restMongoose(router, mongoose);
router.register({ model: User, prefix: '/users' });
app
.use(bodyParser())
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000, () => console.log('Server running on port 3000'));
这个简单的示例展示了如何连接 MongoDB 数据库,定义一个 User 模型,并使用 koa-rest-mongoose
中间件来自动处理与 User 相关的 RESTful 路由。现在,你可以通过 /users
端点进行标准的 CRUD 操作。