Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

563
Views
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}...`)
    })
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!