MongoDB failing to store model information

As I dive into practicing with APIs to hone my skills in creating models and routes, I find myself stuck on getting my initial route to successfully save data to my MongoDB database.

When testing with Postman, I encounter the following error:

{
"message": {
    "errors": {
        "name": {
            "message": "Path `name` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `name` is required.",
                "type": "required",
                "path": "name"
            },
            "kind": "required",
            "path": "name"
        },
        "description": {
            "message": "Path `description` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `description` is required.",
                "type": "required",
                "path": "description"
            },
            "kind": "required",
            "path": "description"
        }
    },
    "_message": "Universes validation failed",
    "message": "Universes validation failed: name: Path `name` is required., description: Path `description` is required.",
    "name": "ValidationError"
}

My code for the model and route sections is as follows:

const mongoose = require('mongoose');

const UniverseSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date : {
        type:  Date,
        default: Date.now
    }
});

//export the route ---------------------Name in db , schema that it should use
module.exports = mongoose.model('Universes', UniverseSchema);

const express = require('express');
const router = express.Router();
const Universe = require('../models/Universe');

// Initial route that will render our universes page
router.get('/', async (req , res) => {
    res.send('Universes Page');
    try {
        const universes = await Universe.find();
        res.json(universes);
    } catch (error) {
        res.json({ message: error });
    }
});

// Route used to create a universe
// Create async our post 
router.post('/', async (req, res) => {
    // Create an instance of the Universe model
    const universe = new Universe({
        name : req.body.name,
        description : req.body.description
    });
    // Attempt to save our new universe with a try-catch block
    try {
        const savedUniverse  = await universe.save()
        res.json(savedUniverse);
        console.log('saved');
    } catch (error) {
        res.json({ message: error});
        console.log('Not saved');
    }
});

module.exports = router;

When sending data via Postman using a POST request, I include an object with the following structure: { "name":"test1", "description":"test description 1" } Here is my App.js file, which also includes the body-parser setup:

//Server setup
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv').config();

//Middleware
app.use(bodyParser.json());

//index Route
app.get('/' , ( req , res ) => {
    res.send('index');
});
// Import routes
const universeRoute = require('./routes/universes');
app.use('/universes', universeRoute );

//Connect to DB
mongoose.connect(process.env.DB_CONNECT,
     { useNewUrlParser: true } ,
     () => {
    console.log('Connected to DB');
});

app.listen(process.env.PORT || 5000);

All help and insights are greatly appreciated.

Answer №1

If you are having issues with sending data to your API and parsing it, there may be a solution:

Consider the following steps:

  1. When using Postman, opt for the commonly used method of sending data through POST requests. Use the "raw" format and send the data as application/json. https://i.sstatic.net/IBjhd.png

  2. On the API side, ensure that you can parse application/json requests. The preferred package for this within Express is expressjs/body-parser

const mongoose= require('mongoose')
const express = require('express')
const bodyParser = require('body-parser')
const Universe = require('../models/Universe')

const app = express()

// Establish connection with MongoDB
mongoose.connect(/* MongoDB connection string */, /* Connection options */);
mongoose.connection.on('error', err => {
  console.error('MongoDB connection error: ' + err)
  process.exit(-1)
})

// Parse JSON
app.use(bodyParser.json({ type: 'application/json' }))

// Initial route to display universes page
app.get('/', async (req , res) => {
  res.send('Universes Page')
  try {
      const universes = await Universe.find()
      res.json(universes)
  } catch (error) {
      res.json({ message: error })
  }
});

// Route for creating a new universe
// Asynchronously create our post 
app.post('/', async (req, res) => {
  // Create a new instance of the Universe model
  const universe = new Universe({
      name : req.body.name,
      description : req.body.description
  })
  // Try saving the new universe
  try {
      const savedUniverse  = await universe.save()
      res.json(savedUniverse)
      console.log('saved')
  } catch (error) {
      res.json({ message: error})
      console.log('Not saved')
  }
});

app.listen(3000)

Don't forget to validate bodies before processing them :)

I hope this information proves helpful!

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

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...

Is it advisable to opt for window.webkitRequestAnimationFrame over setInterval?

Trying to figure out the best method for moving game characters in my JavaScript game - should I go with window.webkitRequestAnimationFrame or stick with setInterval? Any advice is appreciated! ...

What is the best way to insert HTML elements in front of other HTML elements using a form and jQuery?

I am looking to insert new HTML elements before existing ones using a form and jQuery: Here is the initial HTML Code: <div class="main-content"> <h2 class="main-content-header">Projekte</h2> <div class="project-content"> ...

Creating a WasmModuleBuilder in V8 that enables functions to return multiple values

I'm currently working on creating a wasm function using WasmModuleBuilder from V8: var builder = new WasmModuleBuilder(); builder.addMemory(5, 5, false); builder.addFunction("func", {params: [125,125], results: [125,125]}); builder.functions[0].addBo ...

Node.js and Express 3 framework problem with session termination

Having an issue with deleting a specific session in my nodejs Express 3 framework. Here is the code I'm using: app.js var express = require('express'); ................ ................ app.use(express.cookieParser()); app.use(express.se ...

Speed up the opening and closing of a div element on mouse hover

Looking to create a smooth delay for opening and closing a div when mouse hover. Here is the code I have: function show_panel1() { document.getElementById('hoverpanel1').style.display="block"; } function hide_panel1() { document.getElementByI ...

Strange Node.js Issue

I don't have much experience with node.js, but I had to use it for launching on Heroku. Everything was going smoothly until a few days ago when suddenly these errors started appearing. Error: /app/index.jade:9 7| meta(name='viewport', co ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

Mastering the art of integrating Poet with Node.js, Express, and EJS for seamless web development

Recently, I stumbled upon the innovative Poet blog engine and I am intrigued to learn how to integrate it with the EJS template engine. Despite going through the documentation, I'm still puzzled about the process of creating a new post, the required ...

Inserting a new key-value pair into each object within an array

I have a collection of items that I need to add a specific key to in AngularJS using $scope. The following code shows the initial objects: $scope.Items = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sw ...

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Obtain the parameter value from the resolve function in ui-router

Using window.open, I plan to open a URL such as https://localhost:3000/new?HostId=8Ocs_Onuv1wowozxAAAS&_host_Info=excel%7Cweb%7C16.00%7Cen-us%7Cc8b501ce-c51d-b862-701e-5c623e1a70e0%7CisDialog. The site https://localhost:3000 hosts a MEAN stack applica ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...

Querying multiple collections in MongoDB: accessing data from more than two document sets

There are 2 collections stored in MongoDB. collection1 **user's** _id:ObjectId("5a1bedd219001b168e33835e") password:$2a$05$H5wz7kCm/UIGYpvGWruV0eRd.Blgndd4i8pzZcyW7uCG3U4kUzZM2 socket_id:ljlZzY73BZjnwjZBAAAD nickName:des email:<a href="/cdn-cgi/ ...

What could be the reason my div is not being hidden in jQuery?

Creating a quiz layout for school is my current project, and I'm just getting started. My goal is to have the questions disappear once the 'next question' button is clicked. The issue arises after the second question because instead of the ...

Deliver JavaScript and HTML through an HTTP response using Node.js

My attempts to send both a JavaScript file and an HTML file as responses seem to be failing, as the client is not receiving either. What could be causing the client to not receive the HTML and JavaScript files? I am using Nodejs along with JavaScript and H ...

AngularJS DataGrid export options

Utilizing the angular-datatable plugin, complete with export buttons. You can see an example here: vm.dtOptions = DTOptionsBuilder.fromSource('data.json') .withDOM('frtip') .withPaginationType('full_numbers') // ...

Using JavaScript to manipulate an HTML canvas

I currently have an index.hTML file that is set up to display a canvas using the following code: <body> <canvas> </canvas> <script src="./JS/index.js" type="module"></script> </body> Within my JavaScript fi ...