What causes the malfunction of the save function in express?

Today marks my first venture into using Express. I attempted to create a straightforward route, but unfortunately, my save function is not cooperating. Despite scouring similar inquiries on stackoverflow, I have been unable to find a solution. Any assistance you can provide would be greatly appreciated.

const express = require("express");
const router = express.Router();
const Post = require("../models/Post");

//ROUTES

router.post('/', (req, res) => {
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    })

    post.save()
    .then(data => {
        res.json(data);
    })
    .catch(err => {
        res.json(err);
    }); 
});

module.exports = router; 

Below is the model I am working with:

const mongoose = require("mongoose");

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Posts', PostSchema);

Here is an excerpt from my app.js file:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");

//IMPORT ROUTES
const postsRoute = require("./routes/posts");

//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
app.use('/posts', postsRoute)

//ROUTES
app.get('/', (req, res) => {
    res.send("We are on home");
});

//CONNECT TO DB
mongoose.connect(
process.env.DB_CONNECTION, 
{ useNewUrlParser: true },
() => {
    console.log("DB Connected!!")
})

//How do we start listening to the server
app.listen(3000);

My Postman query screenshot - https://i.stack.imgur.com/PrgUK.png

Response received in Postman - https://i.stack.imgur.com/52kuI.png

Please feel free to reach out if more information is needed.

Answer №1

Your app.js file should look like this:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");

// Middleware - Function that always executes when routes are being hit.
app.use(bodyParser.json())

mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true }, function(err) {
    if (err) {
        console.error('System could not connect to MongoDB server')
        console.log(err)
        process.exit()
    } else {
        console.log('System connected to MongoDB server')
    }
});

// Routes
app.get('/', (req, res) => {
    res.send("We are on the home page");
});

// Import routes
const postsRoute = require("./routes/posts");

app.use('/posts', postsRoute)

app.listen(3000);

Also, add a console log in the router to check req.body:

router.post('/', (req, res) => {
    console.log('req.body ===', req.body);
    ...
});

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

"Maximizing efficiency with Azure Functions, Azure SQL, Node.js, and optimized connection pooling for seamless

I'm curious - is it possible to implement an Azure SQL connection pool for Azure Functions (Node.js) requests? The time it takes to create a connection is a significant portion of the overall execution time of my requests, and I'm interested in ...

Blazor combines the power of both C# and JavaScript by allowing them to be executed in a single

There is a button that triggers a JavaScript function: <button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button> And there is another button that executes C# code and toggles ic ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Unable to retrieve hours from MongoDB date array

Whenever I fetch data from my NodeJS+MongoDB webservice, I am able to retrieve the date format successfully. However, I am facing an issue when trying to extract hours from it. Here is how the date looks in MongoDB: https://i.stack.imgur.com/qxWGL.png I ...

Is there a way to instruct npm to compile a module during installation using the dependencies of the parent project?

I am curious about how npm modules are built during installation. Let me give you an example: When I check the material-ui npm module sources on GitHub, I see the source files but no built files. However, when I look at my project's node_modules/mate ...

"Step-by-step guide on using JavaScript to print a PDF file stored locally

As an illustration, I have a local PDF file with 6 pages. When using the window.print() function, only one page is displayed in print preview regardless of what is shown in the browser. Instead of just one page, all pages should be visible in print previ ...

What is the best way to filter out the output from the `mongo-express` node express middleware in the terminal?

Upon visiting my local installation of the Mongo-Express Web Interface in a browser, I am presented with a layout as depicted below: https://i.stack.imgur.com/PWcXO.png However, when inspecting the console, I notice that it displays all the resour ...

I am experiencing an issue with environment variables not appearing in my Context component on Next.js. Should I adjust the Next.js configuration or set up the Context to properly utilize the variables?

Why are Environment Variables working on every component inside /pages but not in my Context component in Next.js? Do I need to do some configuration in Next.js for this? (Note: The Shopcontext.tsx file is using a class component that I obtained from a tu ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

Convert price to Indonesian Rupiah currency format with the help of Vue.js

Can someone help me convert the price format from IDR 50,000.00 to IDR 50.000 using JavaScript and Vue? I found a script on this website, but I am having trouble understanding how it works. The script looks like this: replace(/(\d)(?=(\d{3})+(?: ...

Sending an array as JSON data to PHP using the $.ajax post method. The $_POST array is

After spending a considerable amount of time on this, I'm still struggling to figure out what I'm doing wrong. I'm having difficulty retrieving the data in the PHP file. I've made multiple calls to "copy" to populate the "result" arr ...

unable to execute a node.js demonstration

When attempting to run a pre-existing example in the node.js environment, I consistently encounter the error message: "Cannot find module '/build/default/validation'" Could it be possible that I forgot to install a certain module using npm? ...

What is the method for retrieving the name of an object's property within an Angular template

I am trying to display the name of a nested object's property using Angular interpolation <ng-container ngFor="let item of saleDetailsAggegater.productMap | keyvalue"> <tr *ngFor="let qtyMap of item.value | keyvalue"&g ...

The JSON data sent from the primary Electron process is arriving as undefined in the renderer

Currently delving into an Electron project to explore the technology. It's been a captivating and enjoyable experience so far as I work on creating a basic home controller for my IoT devices. However, I've encountered a minor issue. In my main.js ...

Access-Control-Allow-Methods is not permitting the use of the DELETE method in the preflight response for Angular 2

I am having trouble deleting a record in mongodb using mongoose. Here is the code snippet from my component: deleteProduct(product){ this._confirmationService.confirm({ message: 'Are you sure you want to delete the item?', ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Bootstrap - creating seamless navigation between accordion sections on a single webpage

I am currently attempting to create internal links within an accordion menu on the same page. Here is the code I have been working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> & ...

How can I retrieve JSON data from within a function and show it on a textfield in Swift programming language?

I've been exploring how to parse JSON data into Swift, specifically attempting to display the area of my pincode in a text field. In order to do this, I've created three Swift files: mapview.swift, maphandler.swift, and mapmodel.swift. The issue ...