What is the way to instruct Mongoose to exclude a field from being saved?

Is there a way in Mongoose to instruct it to not save the age field if it's null or undefined?
Or is there a method to achieve this in Express?

Express

router.put('/edit/:id', function(req, res) {
    Person.findOneAndUpdate({ _id: req.params.id }, {
        name: req.body.updateData.name,
        age: req.body.updateData.age
       }, { new: true });
})

Mongoose Schema

var PersonSchema = new Schema({
    name: { type: String},
    age: {type: String}
})

An explanation (if you're wondering why I need this)
I'm using the same HTML template for creating a new person and editing an existing person. When creating a new person, Mongoose will only save the name field if the age field is left empty. But when using the edit template, Mongoose always sets the age field as null, even if it's empty. I'm struggling to find a solution to prevent this behavior.

Answer №1

Prior to updating the database, it is possible to manipulate the request data in this manner:

router.put('/modify/:id', function(req, res) {
    let updateInfo = {name: req.body.modifiedData.name};
    if (req.body.modifiedData.age != "") {
        updateInfo.age = req.body.modifiedData.age;
    }
    Person.findOneAndUpdate({ _id: req.params.id }, updateInfo, { new: true });
})

Answer №2

Hey @Aioros, your response sparked some inspiration in me! However, I stumbled upon a different solution that perfectly addresses my current situation. I've decided to remove any null or undefined object elements before sending them over to Mongoose.

let update = {
      name: req.body.updateData.name,
      age: req.body.updateData.age
     };

if (update.age === null || update.age === undefined) delete update.age

Person.findOneAndUpdate({ _id: req.params.id }, update, { new: true });

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

Tips for populating an HTML input with the value of a link element using JQuery

I have a form input that I want to populate with autocomplete suggestions from my database using Ajax. To style the list, I am using bootstrap 4, and I have opted to use the <a></a> tag instead of the <li></li> tag. This is because ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

"What exactly does {...props} refer to and what is the best way to obtain my function from another

Currently, I am focusing on learning react native with a specific interest in react navigation v5. As mentioned in this resource: https://reactnavigation.org/docs/themes/#using-the-current-theme-in-your-own-components, my goal is to implement a dark mode ...

Send the user to the login page once their email has been verified

On my website, I have a process where users need to verify their email by clicking on a link sent through emails. When the user clicks on this verification link, I want them to be redirected to a page thanking them for confirming their account and then a ...

Stop the slideshow when hovering

I have successfully implemented a script for running a slideshow. The script works well and does the job perfectly. jQuery(document).ready(function ($) { setInterval(function () { moveRight(); }, 5000); var slideCount = $('#slider ul li' ...

Swagger is refusing to cooperate because my model's attributes are set to true

Currently delving into Swagger and its documentation functionality through a YAML file. Previously, I had used @swagger in the controller file and everything worked fine. However, when attempting to transition to a YAML file for better organization, issues ...

Clickable Element Embedded within Event Date - Developed with Vue.js

Currently, I am utilizing Vuetify's calendar component. My task involves displaying and concealing specific information within a calendar event upon clicking a button located inside the same event. While I have succeeded in showing or hiding the div e ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

Can I install more than one instance of Framework7 on the same device?

Currently, I am working on a project using cordova 6.2.0 and framework7 1.6.5. However, now I need to initiate a new project that will be based on cordova 7.1.0 and framework7 2.0.7. I am aware that there is version-manager-cordova-software [1] available ...

The issue arises when trying to apply Bootstrap CSS styles to dynamically created elements using JavaScript

I utilized JavaScript to create a Bootstrap Modal and followed the correct classes as outlined in the Bootstrap documentation, but unfortunately, the JavaScript-created elements are not being affected. Even after adding the Bootstrap classes and attribute ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

leveraging hooks in NextJS app router for static page generation

How can I make an action take effect on page-load for the app router equivalent of statically generated pages from static paths in NextJS? Everything is working fine with my page generation: // app/layout.js import Providers from '@/app/Providers&apo ...

Are there any alternative solutions to the onunload event in Chrome, or any other ways to achieve the

After extensive searching for a solution to this issue, including scouring Google Chrome support sites and the Chrome Bug Issues page where the problem has not yet been resolved. Currently, I find myself in a situation where I need to use the onload or onb ...

Steps to verify if the data is already present in the database prior to saving

Hi everyone, I have a query regarding how to perform validations before saving edited or posted data (post or put action) in mongoose! For example, if the action already exists in the database, the user should receive an error notification. I attempted th ...

Repeated URL causes Node to redirect

I am currently working on a project that involves redirecting users if they enter a specific URL, especially for redirecting from a Heroku domain. During my testing phase on localhost, I noticed that the redirect URL keeps getting repeated: http://localh ...

Is it possible to align an entire column to the right in the Material UI Data Grid?

I'm currently exploring Material UI and grappling with a specific challenge. Is there a method within Material UI to create a Data Grid with two columns, one left-aligned and the other right-aligned? I've managed to align the headers as desired, ...

What sets apart express.Router() from using multiple express() objects?

When utilizing the latest express 4 router, it becomes possible to organize various route paths into separate files like the following example: // Inside cars.js const router = express.Router(); router.get('/brands', function(req, res) { ... } ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

A step-by-step guide to creating adorable rounded corners in a DIV element

I'd like to create a stylish rounded corner div on the top-right and top-left edges. I attempted it with the following code: border-top-left-radius: 5em; border-top-right-radius: 5em; Desired look of the div: https://i.stack.imgur.com/EoSvSm.jpg A ...