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

React - Updating state from an external component

I realize that the question I am about to ask may go against some basic principles of using React... however, with this example, I hope someone can assist me in finding a solution to the problem I am currently facing. While this code snippet is not from m ...

Pass a JavaScript variable to a PHP script using AJAX when a button is clicked, with a dynamically set href attribute

This is the current situation: There is a checkbox on each row of a table that represents some information An initially disabled button becomes enabled when any checkbox is checked The button is enclosed by an <a></a> tag as shown: <a>&l ...

Close to completing the AngularJS filter using an array of strings

I'm currently working on developing a customized angular filter that will be based on an array of strings. For instance: $scope.idArray = ['1195986','1195987','1195988'] The data that I aim to filter is structured as fo ...

How come the JavaScript map() function displays my feature when the forEach() function didn't work? This issue arises while working with React and Next

There was an issue with rendering my feature because React did not recognize that the state was changing. By switching from using forEach() to map(), I was able to successfully render the feature as intended. This feature retrieves user subscriptions from ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json [ {"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"}, {"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"}, {"stock": "xyz", "vo ...

When submitting the club form, my goal is to automatically generate a club admin within the user list in activeadmin

My dashboard.rb setup looks like this: ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do # form render 'form' # Thi ...

Implementing Conditional Display of Span Tags in React Based on Timer Duration

In my current React project, I am facing an issue with displaying a span tag based on a boolean value. I need assistance in figuring out how to pass a value that can switch between true and false to show or hide the span tag. I tried two different methods ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

Does the syntax for the $.ajax() function appear to be incorrect in this instance?

I am attempting to use .ajax to retrieve the source HTML of a specific URL (in this case, www.wikipedia.org) and insert it into the body of a document. However, the code provided below is not producing the expected outcome. <!DOCTYPE html> < ...

What is the process for implementing a new requirement for 'confirmed' users when they log in with passport.js?

Looking to enhance the functionality of passport.js by implementing a conditional check to verify if the user account is confirmed. The plan is to insert an 'if statement' towards the end of the code, right after validating the user's email ...

The button is converting my text to a string instead of the integer format that I require

Hello everyone, I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below. (html) <div class="action"> ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

Guide to Embedding Content Script into Local Page

Allow me to give you an overview of the current situation; I am in the process of developing a Chrome extension that conducts searches on specific websites, retrieves the results, and then opens a new tab containing a table where all the results are displ ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...