"findByIdAndUpdate continues to work successfully even when the request body includes parameters that are not defined in

Referenced from This particular tutorial on MERN stack development...

In my mongoose schema, I have defined 4 fields:

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

let Todo = new Schema({
    name: {
        type: String,
        required: true
    },  
    description: {
        type: String,
        required: false
    },  
    comments: {
        type: String,
        required: false
    },  
    done: {
        type: Boolean,
        required: true
    },  
});

module.exports = mongoose.model('Todo', Todo);

I'm using the update route as follows:

todoRoutes.route('/update/:id').post(function(req, res) {
    Todo.findByIdAndUpdate(req.params.id, req.body, function(err, todo) {
        if (err)
            res.status(400).send('Updating item failed: ' + err);
        else
            todo.save().then(todo => {
                res.json('Item updated!');
            }).catch(err => {
                res.status(400).send("Update not possible: " + err);
            }); 
    }); 
});

When sending the following body to the route:

{
    "name": "bla"
}

An "ok" status is returned, and the document is successfully updated. However, when adding an extra field like this:

{
    "name": "bla",
    "unwanted_field": true
}
  • The additional field does not show in the database retrieval although it still returns without error. Why is this happening?
  • Why does the update operation not enforce the "required" fields and allows any updates to go through?

Answer №1

Check out this helpful guide that explains how to use the strict option in Mongoose:

let Todo = new Schema({
    name: {
        type: String,
        required: true
    },  
    description: {
        type: String,
        required: false
    },  
    comments: {
        type: String,
        required: false
    },  
    done: {
        type: Boolean,
        required: true
    },  
},
    { 
        strict: true // By default, this is set to true. If changed to "throw", it will result in an error, as demonstrated in the attached image.
    }
);

Below is an image illustrating the error generated when attempting to input invalid data after implementing the strict: "throw" option:

https://i.stack.imgur.com/gWeu9.png

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

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

When implementing Sequelize and Express, encountering the error "Middleware function required for app.use()"

I encountered an error after adding a new function to the aparelhos.js file: function findAparelho(req, res) { Aparelho.findByPk(req.params.id).then((result) => res.json(result)) } The issue seems to be related to the req.params.id statement, but I ...

Setting up Secure Sockets Layer (SSL) Certificates

Revisiting my previous inquiry found here. I am currently operating an Amazon AWS Instance running Windows Server 2013. I utilized IIS 8 to generate a CSR file which was then used on godaddy.com for SSL certificates. GoDaddy provided me with the followin ...

What is the best way to incorporate a button that can toggle the visibility of the sidebar on my post page?

Check out this post of mine I noticed a button on someone's page that could hide their sidebar and expand it again when clicked. How can I implement this feature? Is it a simple task? ...

Swap out the HTML button element for text once the form is submitted

On the main page, I have a button that opens a modal when clicked. Inside the modal, there is a form with a submit button that closes the modal and returns to the main page. After closing the modal, I want to change the HTML button on the main page to plai ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

Replace the checkbox display heading with a text box in the designated area

I'm new to using kendo ui Currently, I am attempting to show a text box in the first column header. Instead of the checkboxDisplay heading, I want to replace it with a text box. Could someone please provide guidance on how to resolve this issue? Here ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

Zoom feature available on various images

My current setup includes one main image and multiple thumbnails that can be clicked to change the main image. The issue I encountered was when using jqzoom on the main image, the zoomed image would go blank after changing. After researching on stack overf ...

Navigate to a specific section on a different page while excluding a distance of X

I've implemented the script below to execute the action mentioned in the title. <script type="text/javascript"> var jump=function(e) { if (e){ e.preventDefault(); var target = $(this).a ...

Interacting with Rails controllers through AJAX to trigger a JavaScript function

After exploring numerous stack overflow posts without finding a working solution, I decided to seek help for a well-documented use case. I have a button that should perform the following tasks: When clicked, call a custom controller method to update th ...

After refreshing the page, the JQuery radio button will still be selected

In my form, a radio button triggers an additional text field based on user selection. To achieve this functionality, I am using the following jQuery script: $(document).ready(function(){ $('input:radio[name="accountType"]').change(function() ...

Showing attributes of models using Sequelize and Handlebars

As a novice in the world of programming, I am currently immersed in a website project where users can write and post articles. One crucial aspect I am focusing on is displaying the history of articles written by each user on their account page. Despite uti ...

The Multipart Parser encountered an unexpected end of stream error while in the starting state

i encounter this issue when attempting to submit a form link(rel='stylesheet',href='/stylesheets/home/profile/home_menu.css') script(type='text/javascript',src='/javascripts/perfil_editar.js') #logo_usuario img ...

Is there a way to access the initial element of the array within this variable assignment?

When utilizing the element id 10_food_select: var id = $(sel).attr("id").split("_"); An array is generated as follows: ["10", "food", "select"] The desired outcome is to have id = 10 (or whichever value is in the first element). This can be achieved l ...

What steps can I take to make sure that the asynchronous initialization in the Angular service constructor has finished before proceeding?

Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within the class? constructor() { var sock = new SockJS(this._chatUrl); this.stompClient = Stomp.ov ...

What is the best way to add an array to my JSON object in Javascript?

I'm currently in the process of formatting an array into a JSON object for API submission. Struggling to find the right method to transform my array into the desired structure. This is what my array looks like: data: [ ["Lisa", "Heinz", "1993-04 ...

Do we need to perform session checking for login on POST requests as well?

As a novice in the realm of login systems, I have been utilizing session for authentication. Currently, I have set up a login system with session checking specifically for GET Requests, as they can be accessed directly through the browser's address ba ...

Determine the orientation of the object relative to the camera in threejs

I am currently facing a scenario where I need to determine the direction of an object in relation to the camera. While I have methods for detecting if an object is within the camera's view, I am now tasked with determining the directions of objects th ...