What could be the reason for my mongoose model failing to save in mongodb?

I am experiencing an issue with my simple Post model and route for creating posts. After submitting a new post using Postman, the request hangs for a moment before returning an error in JSON format. The model data is never saved successfully.

Below is the structure of my model:

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }

});

And here is the code snippet for my route:

router.post('/', (req, res) => {

    console.log(req.body.title);
    console.log(req.body.body);

    const post = new Post({
        title: req.body.title,
        body: req.body.body
    });

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

I have ensured that all necessary modules are imported correctly. Any assistance would be greatly appreciated!

Answer №1

Consider implementing a try{}catch{} block in your code and let me know if the issue persists:

router.post("/", (req, res) => {
  try {
    const post = new Post({
      title: req.body.title,
      body: req.body.body,
    });

    post.save();
    res.status(200).send(`Post created!`);
  } catch (err) {
    res.status(400).send({ message: err });
  }
});

Additionally, ensure that your model is properly exported:

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    data: {
        type: Date,
        default: Date.now
    }

});

module.exports = mongoose.model("Post", PostSchema);

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

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Switching between three div elements along with two icons can be done by using toggle functionality

Is there a way to make the icon change back when clicked again without making major changes to the existing code? Looking for suggestions on how to achieve this functionality. function myFunction() { var element = document.getElementById("demo"); el ...

Which data store to use with Express on Node?

Embarking on my inaugural project with node/express. Considering implementing a data store and noticed express utilizing redis as a session store. Does this imply that redis comes pre-installed with express? Wondering if I should install mongodb, but if r ...

Troubleshooting the Checkbox Oncheck Functionality

Before checking out the following code snippet, I have a requirement. Whenever a specific checkbox (identified by id cfc1) is clicked, it should not show as checked. I have implemented the onCheck function for this purpose, but I'm struggling to fig ...

Tips for receiving accurate HTML content in an Ajax request

I have used an Ajax call to fetch data from a function that returns an entire HTML table. $.ajax({ url: "/admin/project/getProjectTrackedTimes", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('cont ...

Avoiding JavaScript onclick event using JSON information

Here's a situation I'm dealing with: I have a button created using PHP that triggers a JavaScript onclick event: <button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php e ...

Setting the maximum width for a JavaScript pop-up box

Below is the html code that creates a link reading "sacola de compras" <div> <script type="text/javascript" src="https://app.ecwid.com/script.js?4549118"></script> <script type="text/javascript"> xMinicart("style=","layout=Mini") ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Getting the response from a Node.js fetch call and sending it directly to an Express response involves piping the

How can I forward the response from a nodejs fetch request to an express response? Is it possible to achieve this similar to how it was done with node-fetch modules? const fetchResponse = await fetch(myUrl); fetchResponse.body.pipe(expressResponse); ...

Fetch information from MySQL, create a new row for each data entry

Currently, I am working on a project for my school that involves retrieving student works from a database. For the homepage of my project, I have set up 10 divs to hold the data returned from a query. The reason I preset these divs is because I only need ...

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

The ng-options loop in the array is unable to locate the specified value

In my C# controller, I generate a list and translate it to Json for Angular to receive at the front end. However, when using ng-options to loop through this array in order to get the array value, I always end up with the index instead. <select class="s ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

Create a self-bot that can generate a new server

I am currently working on a discord.js self-bot and I need assistance in creating a server. Any guidance would be greatly appreciated. I have experimented with the client.user method, but did not achieve the desired result. If it is not possible to c ...