简体   繁体   中英

REST API in nodejs and mongodb for blog

I have difficulty increasing the articleCount field of tags schema.

Tag Schema:

let tagSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        required: true
    },
    articleCount: {
        type: Number,
        default: 0
    }
})

The Article shema:

let articleSchema = new Schema({
    ...
    tags: {
        ref: 'tags',
        type: [Schema.Types.ObjectId]
    }
})

So I need that each time a new article is added, all the tags that it's listed are increased by one.

To get something like this:

POST /api/articles

{
    ...
    "tags": ["5bfaaedbfe407d345ba2745b", "5bfab93ff73c0d117bd55ea6"]
}

GET /api/tags

{
    "articleCount": 1,
    "_id": "5bfaaedbfe407d345ba2745b",
    "name": "javascript",
    "createdAt": "1970-06-28T18:09:05.485Z",
    "__v": 0
},
{
    "articleCount": 1,
    "_id": "5bfab93ff73c0d117bd55ea6",
    "name": "css",
    "createdAt": "1970-06-28T18:09:05.485Z",
    "__v": 0
}

How I can do this ?

There are two ways basically.

  1. Find one of the ORM frameworks that helps you generate the MongoDB interface and logic. There are DB-specific ORMs like Mongoose , and there are generic cross-lang, cross-DB ORM framework like Loopback . These usually ask you to provide them a schema and they will generate the API. The advantage is everything is taken care of for you, but need some learning curve, and is less as flexible.

  2. Hand write a limited set of api that you care and set up router path yourself, where as for each routing route, you can create a function and code in the operation details. For this you will need to hand write CRUD for your own schema, maybe each schema individually. The advantage is much faster(when small) dev cycle for a smaller and limited functionalities and greater flexibility.

The Official MongoDB document about REST interfaces is a good place to start digging. https://docs.mongodb.com/ecosystem/tools/http-interfaces/#rest-interfaces

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