Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[].

https://i.stack.imgur.com/qe802.png

The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the post method in a global array named items[].

https://i.stack.imgur.com/QXKDf.png

Here's the code snippet:

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}...`)
    })
})

Answer №1

If you want to send the response in JSON format, you can use res.json() method.

Replace

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

with

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining if a variable has been defined in JavaScript

In my JavaScript code, I declare global variables named with the prefix "sld_label" where "label" can be any string. These variables are initialized as objects that contain a function called setval. Now, I have a function that receives a label in a string ...

a reliable approach to gain entry to properties that do not exist

Utilizing Google Apps Script along with JavaScript code, I am leveraging UrlFetchApp to retrieve data from the Stripe API in order to fetch an invoice. Subsequently, the Script processes the retrieved data and updates a Google Sheet template with it. An i ...

What are some creative ways to design the selected tab?

In my Vue parent component, I have multiple child components. There are several elements that toggle between components by updating the current data. The issue is that I am unsure how to indicate which tab is currently active. I've tried various li ...

Dynamic loading of JavaScript/HTML content using jQuery Mobile and PhoneGap

I am currently in the process of building a mobile app using Dreamweaver CS6 (with PhoneGap), along with jQuery Mobile and JavaScript. This app aims to gather user-inputted form data, convert it into a JSON object, and send it to a python web service. The ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

"Which is the better choice for a Django application's for loop: views.py or

I'm in the process of creating a Django app that features a word list. The app currently utilizes a speech function to inform the user of the first word on the list. The user is then able to record an audio clip of a word they say, which is converted ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

Put the browser into offline mode using JavaScript

Currently, I am utilizing selenium for application testing purposes. Although I typically start my browser in the usual manner, there comes a point where I must transition to offline mode. I have come across various sources indicating that switching to off ...

Angular proxy - Syntax error found in proxy configuration file: proxy.conf.json

My Angular 6 setup is configured to make HttpRequests, but I encountered a problem that requires me to run them through a proxy. To address this issue, I created a proxy.conf.json file next to my package.json: { "/loans/": { "target" : "https://api. ...

Mastering the art of using either promises or callbacks properly

Attempting to retrieve the result of a variable after completing all asynchronous processes in a function. I've discovered that I need to use promises for this, so I spent today learning about them. I've implemented promises in my function and c ...

Guide on transferring a JWT token to a Node.js backend

Recently, I developed a node.js server featuring a login system and am focused on safeguarding my routes. Despite creating middleware to authenticate each protected route, I keep encountering an "Authentication failed" message after logging in. How can I e ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

"Creating dynamic web apps with the powerful duo of Meteor and Zurb

Just starting out with programming and currently working on a new web application using Meteor and AngularJS. I would like to incorporate the elements/css from 'Zurb Foundation For Apps' into my project... I am familiar with including Bootstrap ...

Troubleshooting Problems with Adjusting Left Margin Using JQuery

function adjust_width() { $('#cont').toggle(function(){ $('#cont').animate({marginLeft:'0%'}); },function(){ $('#cont').animate({marginLeft:'18.4%'}); }); } The code above is in ...

What steps do I need to take to transform this click event function into one that is triggered automatically upon the div loading?

In order to automatically load content into a div using innerHTML, the PHP file must be retrieved and the div updated with its content. Within this div is another one labeled "tweet" which displays actual tweets based on a specific hashtag provided through ...

Steps for adding an HTML string to a div element using Ajax

I am facing some major challenges with Ajax, especially when it comes to appending HTML code to a div. I am attempting to append this HTML string to <div id="content-loader"></div> PHP function getLogo(){ $logo = '<div class="bg- ...

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

Using RxJS with Angular to intercept the valueChanges of a FormControl prior to subscribing

I decided to create a new observable using the values emitted by the FormControls.valueChanges observable. This creation of the observable takes place within the ngOnInit method in the following manner: ngOnInit(): void { this.myObservable$ = combine ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

Error: Trying to access 'product-1' property on an undefined object

Having trouble displaying JSON data in my React.js project, I've been stuck on an error for the past couple of days with no luck in solving it. The JSON data is stored in a file named products.json: { "product-1": [ { ...