The document seems to be empty following the MongoDB upload

It seems that none of the values I entered in the form are appearing in the document. Possibly, I'm searching in the incorrect location. Check out my code below:

import mongoose from 'mongoose'
import express from 'express'
import * as dotenv from 'dotenv'
import cors from 'cors'
import bodyParser from 'body-parser'
import MailJet from 'node-mailjet'

// SUGGESTED FIX for: '__dirname is not defined in ES module scope'
import path from 'path'
import { fileURLToPath } from 'url'

// Create Show schema and model
const showSchema = new mongoose.Schema({
    eventTitle: String,
    location: String,
    date: String,
    time: String,
    ticket: String,
    desc: String,
    image: String
})

const Show = mongoose.model('Show', showSchema)

// SUGGESTED FIX for: '__dirname is not defined in ES module scope'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

dotenv.config()

const app = express()
const port = process.env.PORT

// Set CORS and connect
app.use(cors()) 
app.listen(port, () => console.log(`Server listening on port ${port}`))

mongoose.connect(process.env.MONGOOSE_CONNECT)

// Create storage engine
const upload = multer()

// MailJet configuration
const mailjet = MailJet.apiConnect(
    process.env.MAIL_KEY,
    process.env.MAIL_SECRET
)

    // Upload new show 
    app.post('/uploadShow', upload.single(), async function (req, res) {    
        // Convert date
        const dateParts = req.body.date.split('-')
        dateParts.push(dateParts.shift())
        const newDate = dateParts.join('-')
    
        // Convert time
        const timeParts = req.body.time.split(":")
        const daylight = timeParts[0] < 12 ? " AM" : " PM"
        timeParts[0] !== "12" && parseInt(timeParts[0]) !== 0 
        ? timeParts.unshift(timeParts.shift() % 12) 
        : timeParts[0] = "12"
        const newTime = timeParts.join(":") + daylight
    
        // ACCESS BODY, UPLOAD TO MONGODB DATABASE
        const newShow = new Show({
            TITLE: req.body.eventTitle,
            LOCATION: req.body.location,
            DATE: newDate,
            TIME: newTime,
            TICKET: req.body.ticket,
            DESC: req.body.desc,
            IMAGE: req.body.image
        })
    
        await newShow.save().then(console.log('SHOW SAVED')).catch(err => console.log(err))
    
        res.status(200)
        res.send("FORM RECIEVED")
    })
    
    app.post('/contact', bodyParser.json(), function(req, res){
        console.log(req.body)
    
        const request = mailjet.post('send', { version: 'v3.1' }).request({
            Messages: [
                {
                    From: {
                        Email: process.env.SENDER_EMAIL,
                        Name: 'KMAC Music'
                    },
                    To: [
                        {
                            Email: process.env.RECIPIENT_EMAIL,
                            Name: 'KMAC Music Contact Inbox'
                        }
                    ],
                    Subject: `NEW CONTACT from ${req.body.name}`,
                    TextPart: `${req.body.name} writes regarding ${req.body.reason}:\n\n\t${req.body.message}\n\nCONTACT INFO:\n\t${req.body.email}\n\t${req.body.phone}`,
                    HTMLPart: null,
                },
            ],
        })
        request
            .then(result => {
                console.log(result.body)
            })
            .catch(err => {
                console.log(err.statusCode)
            })
    })
    
    app.post('/booking', bodyParser.json(), function(req, res){
        console.log(req.body)
        let day = new Date(req.body.date).toLocaleDateString('en-us', {weekday: "long", year: "numeric", month: "short", day: "numeric"})
    
        const timeFunc = (dateString) => {
            const timeArr = dateString.split(':')
            const hour = Number(timeArr[0]) % 12
            const ampm = Number(timeArr[0]) < 12 || Number(timeArr[0]) === 24 ? 'AM' : 'PM'
    
            return `${hour}:${timeArr[1]} ${ampm}`
        }
    
        const request = mailjet.post('send', { version: 'v3.1' }).request({
            Messages: [
                {
                    From: {
                        Email: process.env.SENDER_EMAIL,
                        Name: 'KMAC Music'
                    },
                    To: [
                        {
                            Email: process.env.RECIPIENT_EMAIL,
                            Name: 'KMAC Music Contact Inbox'
                        }
                    ],
                    Subject: `NEW bOOKING REQUEST from ${req.body.name}`,
                    TextPart: `${req.body.name} would like to book your services!\n\n\tDATE: ${day}\n\tTIME: ${timeFunc(req.body.time)}\n\tDESCRIPTION:\n\t\t${req.body.description}\n\n\tCONTACT INFO:\n\t\t${req.body.email}\n\t\t${req.body.phone}`,
                    HTMLPart: null,
                },
            ],
        })
        request
            .then(result => {
                console.log(result.body)
            })
            .catch(err => {
                console.log(err.statusCode)
            })
    })

This issue pertains to app.post('/uploadShow') line 50. After saving newShow, here's how the MongoDB document looks:

{"_id":{"$oid":"63532b09c95d57d1e52710ff"},"__v":{"$numberInt":"0"}}

The values for newShow are missing. Could there be an error with the upload process? Or perhaps the data isn't where it should be? Any guidance on this matter would be greatly appreciated.

Answer №1

When you are beginning a new document, it's crucial to pay attention to the attributes specified in the schema declaration.
Additionally, make sure not to combine await and then. Here is how you can approach it:

try {
  const newlyCreated = await Document.create({
    title: req.body.title,
    content: req.body.content,
    date: currentDate,
    time: currentTime,
    author: req.body.author
  });
  res.status(200).send('DOCUMENT SAVED SUCCESSFULLY');
} catch (error) {
  res.status(400).send('ERROR OCCURRED');
}

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

The function in Mocha triggered multiple calls to the done() method within Mongoose

I've created a test suite to verify user registration: const chai = require('chai'); const chaiHttp = require('chai-http'); const { app } = require('../../'); const {User} = require('../../models/'); chai.use( ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

Using jQuery to rearrange an ordered list by moving items with a specific class to the top

Is there a way to use jQuery to rearrange ordered list items with a specific class and move them to the top of the list? Consider the following snippet of HTML code: <div id="notice">click here</div> <ul> <li>Coffee</li> ...

Pause and Persist

Can someone help me clarify a code issue I'm facing? I have a piece of code that checks an array for overlapping values based on different criteria. This code specifically deals with rows and columns in a Google Sheet using GAS. Here's what I cur ...

Passing PHP data to a JavaScript file using JSON格式

I have a query regarding how to pass php variables and send their values to a js file using json. Here is what I currently have: <?php $data = array('artist' => $artistname, 'title' => $songname); echo json_encode($data); // ...

The Debate: Single Javascript File vs. Lazy Loading

Imagine you're working on a massive javascript-powered web application with minimal page refreshes in mind, containing around 80-100MB of unminified javascript to give an idea of its scale. The theory is that by lazy-loading your javascript files, yo ...

Refreshing a single HTML element in ASP.NET MVC - the simple way!

Recently, I put together an image gallery using the unite gallery jquery plugin and now I want to change up the images it displays. My plan is to have a button labeled "art" that, when clicked, triggers a function to update the directory path and load ne ...

Angular 4 showcases the information stored within this dataset

The data returned from an API to my Angular 4 application is not to my liking. Here is an example of the JSON, where I am only interested in the coin and its price: Goal is to display this data on the page: Coin Price BTC $4,281.28 ETH $294.62 ...

How to implement a link_to tag in autocomplete feature with Rails

I'm having trouble adding a link to the show page in autocomplete results. Although my jQuery alert box is working fine, I can't seem to apply CSS to a div using jQuery. Here's the code snippet I've posted below: //application.js ...

What is the optimal method for navigating through a complex nested object in Angular?

Looking to navigate through a nested object structure called purchase. Within this structure, there is a sub-array named purchaseProducts which contains another sub-array called products along with additional data. What methods do you suggest for efficien ...

What happens if I attempt to pass a blank field in multer?

I am trying to verify if the image field passed to Multer will include the file. There are no errors being thrown by Multer and the server is currently processing the request. ...

What is the method for performing a spelling check on every property within an array of Objects?

I'm working on a program that takes a user input as an argument and then searches for a similar match in an array of objects. The array of objects is retrieved from a database. When the user inputs a name, the search criteria should find objects with ...

Resolving issues with JavaScript onchange functionality

When I try to use both of these scripts (inline and external) together, only the second one seems to be working while the first one does not. The first script (inline) is responsible for submitting the form and loading the list: <select id="my-sel ...

Images, videos, and audios fail to load on Vercel

I created a quirky Vercel app that poses a 'yes or no' question: "Do you want to see my dog?" If the answer is yes, my dog will appear with a woof audio; if the answer is no, you'll get jumpscared. It was just done for fun, using simple HTML ...

The functionality of Jquery-chosen appears to be malfunctioning when applied to a select element

I am encountering an unusual issue with Jquery-Chosen. There is a multi-select box within a pop-up where the options are populated using an ajax call. Strangely, Jquery-Chosen does not seem to work on it. However, if I use a static multi-select box in the ...

Encountering a react error following the installation of FontAwesome via npm

I successfully installed fontawesome by visiting their official website and following the steps below: 1. npm i --save @fortawesome/fontawesome-svg-core 2. npm install --save @fortawesome/free-solid-svg-icons 3. npm install --save @fortawesome/react-fon ...

What are some effective methods to completely restrict cursor movement within a contenteditable div, regardless of any text insertion through JavaScript?

Recently, I encountered the following code snippet: document.getElementById("myDiv").addEventListener("keydown", function (e){ if (e.keyCode == 8) { this.innerHTML += "&#10240;".repeat(4); e.preventDefault(); } //moves cursor } ...

Locating data with object containing a specific String value

In my database, there is a collection with documents structured like this: { "person-name" : "Hughart, Ron", "info" : { "birthnotes" : [ "Los Angeles, California, USA" ], "birthdate" : [ "18 June 1961" ], "birthname" : ...

Properly defining a DI service in Angular 2.1.2 using ES5

I have created an Angular 2 service that utilizes the Http service and is accessed by other components. However, I am unsure if my implementation is correct: (function (app) { 'use strict'; app.LoaderService = ng.core.Component({ providers: ...