expressrestapi路由器与Mongoose模式设计
我正在学习如何使用Mongoose(MongoDB)创建RESTAPI 我正在尝试用Mongoose开发一个快速RESTAPI。我试图做的很简单,但我不确定设计RESTAPI端点和Mongoose模式的方法 我现在有用户模式,每个用户对象只有用户名和密码。要列出、添加、修改和删除用户,我有一个/api/users端点 models/user.js:expressrestapi路由器与Mongoose模式设计,rest,express,mongoose,database-design,Rest,Express,Mongoose,Database Design,我正在学习如何使用Mongoose(MongoDB)创建RESTAPI 我正在尝试用Mongoose开发一个快速RESTAPI。我试图做的很简单,但我不确定设计RESTAPI端点和Mongoose模式的方法 我现在有用户模式,每个用户对象只有用户名和密码。要列出、添加、修改和删除用户,我有一个/api/users端点 models/user.js: const userSchema = new mongoose.Schema({ username: { type: Str
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
routes/users.js
router.get('/', async (req, res, next) => {
// List all users
});
router.get('/:id', async (req, res, next) => {
// Get user with specified id
});
router.post('/', async (req, res, next) => {
// Create user with given body
});
router.put('/:id', async (req, res, next) => {
// Update user with given id and body
});
router.delete('/:id', async (req, res, next) => {
// Remove user with given id
});
现在,我想做的是让用户拥有文档。他们将能够创建文档、重命名文档、更改文档或删除文档。我搜索了我应该如何在我的API中实现这个想法,并找到了3个选择
users.js
路由器端点。我是否应该为这些操作创建另一个路由器文件,如routers/documents.js
,并使用端点,如/api/documents/
?如果是这样,我需要什么样的端点,比如router.get('/:userId/')、router.get('/:userId/:documentId')
等等。?或者我应该在现有用户路由器中添加新的端点,如/api/users/:id/add_document/,/api/users/:id/documents/
等
提前谢谢。关于您的第一个问题,请访问我的答案:
对于第二个问题,我将按照关注点分离模式创建一个单独的路由器文件,关于端点,我将选择
router.get('/:userId/:documentId')
,因为如果我理解正确,每个文档都属于一个用户。谢谢你的回答。我想我已经按照你的建议解决了关于路由器/端点的问题。