The latest changes in the MongoDB route and model may result in either data deletion or an error being thrown

I've been searching for quite some time now, and I haven't found a similar issue to the one I am facing.

Working on a MERN stack application with four routes, three are functioning properly. However, the fourth route and the database model are causing me trouble.

Below is the model:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let bucketListItem = new Schema({
itemOnList: { type: String, required: true },
status: { type: String, required: true },
dateCreated: { type: Date, default: Date.now },
completed: { type: Boolean, default: false }
});

module.exports = mongoose.model("bucketListItem", 
bucketListItem);

The JSON used in Postman for testing the update function is as follows (derived from a GET request):

{
"completed": true,
"_id": "5c8b05c701eb8007dceb3aaa",
"itemOnList": "Visit Venice",
"status": "btdt.",
"dateCreated": null,
"__v": 0
}

Despite all fields being filled as per the model, updating any field results in an error indicating that the two 'required' fields must be filled.

Error message received:

{
"error": {
    "errors": {
        "status": {
            "message": "Path `status` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `status` is required.",
                "type": "required",
                "path": "status"
            },
            "kind": "required",
            "path": "status"
        },
        "itemOnList": {
            "message": "Path `itemOnList` is required.",
            "name": "ValidatorError",
            "properties": {
                "message": "Path `itemOnList` is required.",
                "type": "required",
                "path": "itemOnList"
            },
            "kind": "required",
            "path": "itemOnList"
        }
    },
    "_message": "bucketListItem validation failed",
    "message": "bucketListItem validation failed: status: Path `status` is required., itemOnList: Path `itemOnList` is required.",
    "name": "ValidationError"
  }
}

Removing the 'required: true' from the model eliminates the error message, but also wipes data from the database entry completely.

{       
 "completed": false,
 "_id": "5c8b05c701eb8007dceb3aaa",
 "__v": 0,
 "dateCreated": "null"
}

The code for my route:

blRoutes.route("/update/:id").post(function(req, res) {
BucketListItem.findById(req.params.id, function(err, 
bucketListItem) {
if (!bucketListItem) {
  res.status(404).send("Data not found.");
} else {
  bucketListItem.itemOnList = req.body.itemOnList;
  bucketListItem.status = req.body.status;
  bucketListItem.dateCreated = req.body.dateCreated;
  bucketListItem.completed = req.body.completed;

  bucketListItem
    .save()
    .then(bucketListItem => {
      res.json("Updated.");
    })
    .catch(err => {
      res.status(400).send({ error: err });
      console.log(err);
    });
  }
});
});

app.use("/bucketList", blRoutes);

Body Parser and CORS have been implemented in my setup.

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Any feedback or help is greatly appreciated.

UPDATE:

A refactored version of my route:

blRoutes.route("/update/:id").post(function(req, res) {
BucketListItem.findOneAndUpdate({ _id: req.params.id }, req.body, {upsert: true, returnNewDocument: true})
.then(bucketListItem => res.json(bucketListItem))
.catch(err => res.status(404).send(err));
});

Additionally, the model has been updated slightly:

let bucketListItem = new Schema({
itemOnList: { type: String, required: true },
status: { type: String, required: true },
dateCreated: { type: Date, default: Date.now() },
completed: Boolean
});

Running this code does not yield the desired changes in the document. The data remains unchanged.

{
"dateCreated": null,
"_id": "5c8b05c701eb8007dceb3aaa",
"completed": false,
"itemOnList": "Visit Venice",
"status": "Bought tickets.",
"__v": 0
}

Your assistance is highly valued. Thank you for your support.

Answer №1

To update the document, use this query:

BucketListItem.findOneAndUpdate(
 { _id: req.params.id },
 req.body,
 { new: true, upsert: true }
);

When defining fields in a schema, you can simply specify the type as Boolean instead of using an object with type. No need to mention default as false.

let bucketListItem = new Schema({
itemOnList: { type: String, required: true },
status: { type: String, required: true },
dateCreated: { type: Date, default: Date.now },
completed: Boolean
});

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

Guide on triggering a modal upon receiving a function response in React

I am looking for a way to trigger a function call within a response so that I can open a modal. Currently, I am utilizing Material UI for the modal functionality. Learn more about Modals here The process involves: Clicking on a button Sending a request ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){ for (var i = 0; i < keywords.length; i++) { var key = keywords[i]; if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + ...

Convert form data into a JSON object utilizing JQuery and taking into account nested JSON objects

Currently, I am facing an issue while extracting data for submission using the jQuery `serializeArray()` function. This function works efficiently by providing an array of { name: value } objects, where the name corresponds to the elements in the form. How ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Using Selenium to trigger a click event on an ng-click directive in AngularJS is not functioning properly

I am currently trying to confirm that a specific external function is being called when an ng-click event occurs. The code for the input declaration is shown below. While everything seems to be functioning properly in browsers, I am encountering issues dur ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

The findDeleted function in mongoose-delete fetches all items with a deleted flag set to both true and false

In my project, I am utilizing the mongoose-delete library. Once data is soft deleted, it gets stored in a recycle bin (I retrieve soft deleted data using findDeleted). const Course = require("../models/Course"); const { mutipleMongooseToObject } ...

Transmitting form information to a nested page within a div container

This is my fourth attempt to seek an answer to this question, as I've faced downvotes in previous attempts. So here we go again. I am trying to send data from a hidden input within a form using ajax. The value of the hidden input is generated by a php ...

I'm not satisfied with the value of the ReactJs state after the change

I am working on creating a calendar app for practice purposes. Currently, I have a current_month state variable set to 1. Additionally, I have a function called IncreaseMonth() that is designed to increment the value of current_month. However, when the va ...

Gather data on webview requests and their corresponding responses

In my app, I am developing a feature that allows users to browse the web using a webview element. <webview src='user-generated'></webview> I am trying to find a way to capture all requests and responses generated during this process ...

Error message: When trying to use express session with Socket.IO, the response from the

Currently, I am working on implementing session management using express 4.x and socket io 1.4, while following guidance from this referenced answer. However, I have encountered an issue where the second argument to the express session function is returnin ...

Hide or show list items in an unordered list using jQuery

I am interested in creating a script that can toggle between "show more" and "show less" functionality for elements in a list. I came across this script: HTML <ul id="myList"> <li>One</li> <li>Two</li> <li> ...

Why is there a Mongoose/Express CastError occurring for just one of two identical routes?

My goal is to retrieve all documents within a collection using two identical express routes. One route successfully returns all documents without any issues. However, on a different express route with the same logic, I encounter the following error: Cast ...

Creating PropTypes from TypeScript

Currently in my React project, I am utilizing TypeScript along with PropTypes to ensure type checking and validation of props. It feels redundant to write types for both TypeScript and PropTypes, especially when defining components like ListingsList: inte ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

I am looking to concatenate the existing URL with the language segment using jQuery

Looking to update the URL when clicking on a language name? Simply add the current path after the language section. For example, change the URL https://example.com/de_DE/about-us/ to https://example.com/us_EN/about-us/ and vice versa. I attempted this code ...

Exploring the world of middleware in Express

I'm exploring the workings of middleware in Express. While I grasp the general idea of middleware, I find myself puzzled by the parameters involved. For instance, consider this snippet from the official middleware documentation: app.use('/user ...

Does a browser's cache utilize storage for XMLHttpRequest responses?

I have a question regarding browsers in general, with a focus on Chrome. Imagine I have the following code snippet in my file, index.html: <img src='//path/to/foo.img'></img> The file foo.img changes on my server every hour. I woul ...