how to split json into stages. Express API

So the problem takes place in architecture of my API, that I want to place into the array, called items[].

enter image description here

As we can see, here is a simple API wrote on express + mongodb. But the question is how to place my data from post method into the global array called items[]. It should looks like:

enter image description here

So the code is:

const express = require('express')
const MongoClient = require('mongodb').MongoClient
const ObjectId = require('mongodb').ObjectId
const app = express();
let db;
const port = process.env.PORT || 3015
app.use(express.json());
app.use(express.urlencoded({ extended: true }));



app.get('/', (req, res) => {
    res.send('Hey')
})

app.get('/artists', (req, res) => {
    let count = 10
    let page = 0
    req.query.count ? count = req.query.count : null
    req.query.page ? (page = req.query.page * count, count = page + 5) : null;
    db.collection('artists').find().toArray((err, docs) => {
        if (err) {
            console.log(err)
            return res.sendStatus(500)
        }
        res.send(docs.slice(page, count))
    })
}),

app.post('/artists', (req, res) => {

    const artist = {
               name: req.body.name,
               photos: {
                   small: null,
                   large: null
               },
               status: null,
               followed: false
   }

   db.collection('artists').insertOne(artist, (err, result) => {
       if (err) {
           console.log(err)
           return res.sendStatus(500)
       }
       res.send(artist)
   })
})





MongoClient.connect('***********', (err, client) => {

    if (err) {
        return console.log(err)
    }

    db = client.db('mongod');

    app.listen(port, () => {
        console.log(`API is listening on port ${port}...`)
    })
})

1 answer

  • answered 2021-10-24 19:24 ABDULLOKH MUKHAMMADJONOV

    You can do this easily with res.json() which sends the response as json data.

    Change

    res.send(docs.slice(page, count))
    

    to

    res.json({ items: docs.slice(page, count), status: "success" })
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum