简体   繁体   中英

MongoDB RESTful API structuring

So, I'm trying to create a RESTful API that works similar to reddit, where it has users, topics(subreddits), posts and comments. For that I'm trying to use Node.js and MongoDB.

This is the github repo so far: https://github.com/edmassarani/reddit-clone

The only problem is I don't know how to structure the deletion of documents and it's "dependencies" because a user might own a topic, that topic has posts, those posts have comments and those comments have authors, so how would I go about deleting a user without leaving behind a topic with no owner or a post with no topic and so on? Would it be easier if I were to use a relational database?

I can see on your Github repo that your structured your models like in a relational database (note : you named relational db as 'SQL database' on your question) with normalized data models :

Example : In Topic.js, you refer Posts with reference :

posts: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Post',
    },
  ],

It certainly works like it, but with NoSQL and specially with MongoDB you have possibility to embed documents into another document.

Why do not embed Post schema directly into Topic like it :

  posts: [
    {

    title: {
        type: String,
        required: true,
      },
      body: {
        type: String,
        required: true,
      },
      ...
      upvotes: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
      ],
      comments: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Comment',
        },
      ],
    },
  ],

As I can understand, if a Topic is deleted, all Posts related to this Topic have to be deleted.

With embedded schema, you have only one deletion to do.

I don't know if in your context embedded is the best solution (because of perfs), but you have two solutions :

  • Use different schema (your models files) and you have to manually delete in cascade (exemple : when you delete a Topic, you have to find all Posts references into the Topic and delete them...)
  • Refactoring and embed : with it, deleting the Topic is also deleting Comments.

See mongodb official docs for more information on embedded schema : https://docs.mongodb.com/manual/core/data-model-design/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM