Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
expressrestapi路由器与Mongoose模式设计_Rest_Express_Mongoose_Database Design - Fatal编程技术网

expressrestapi路由器与Mongoose模式设计

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

我正在学习如何使用Mongoose(MongoDB)创建RESTAPI

我正在尝试用Mongoose开发一个快速RESTAPI。我试图做的很简单,但我不确定设计RESTAPI端点和Mongoose模式的方法

我现在有用户模式,每个用户对象只有用户名和密码。要列出、添加、修改和删除用户,我有一个/api/users端点

models/user.js:

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个选择

  • 规范化:创建另一个名为documents的Mongoose模型,并引用用户模型中的文档

  • 非规范化(嵌入):在用户模型中添加文档属性,并将每个文档直接添加到用户对象中

  • 混合:如果我的文档模型有很多属性,我应该单独创建文档模型,并提供对用户对象的引用以及存储在用户对象中的必要文档数据

  • 我的文档模型中没有很多属性,我想我只需要文档模型中的path和dateCreated属性。所以,我将使用第一个或第二个选项。我应该用哪一个?对于这种特殊情况,有没有更好的方法

    我的第二个问题是关于列出、添加、更改和删除用户文档的
    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')
    ,因为如果我理解正确,每个文档都属于一个用户。

    谢谢你的回答。我想我已经按照你的建议解决了关于路由器/端点的问题。