Update only the given form fields in a Mongoose subdocument

I needed to update a mongoose subdocument based on the fields filled out in a form. The update process is working correctly, but I am facing an issue where if any field is left empty in the form, the update deletes those fields in the subdocument. Instead, I want it to only update with the fields provided in the form and leave the rest as they are. Here is the current update function I am using:

List.updateOne(
        {"questionSet._id": questId},
        {
            $set: {
                "questionSet.$": req.body
            }
        },
        {new: true, useFindAndModify: false},
        (err)=>{
            if(err){
                console.log(err);
                res.redirect("/admin-edit-quest")
            } else {
                res.redirect("/admin-edit-quest")
            }
        }
    )

Here is an example of my mongoose model structure:

list: { "_id" : ObjectId("60f2cc07275bbb30d8cb268e"), 
"listName" : "dsa", 
"aboutList" : "dsa queestions",
 questionSet" : [ { "solved" : false, 
                   "_id" : ObjectId("60f2cc12275bbb30d8cb2695"), 
                    "topic" : "array", 
                     "name" : "array is best", 
                    "url" : "www.arr.com", 
                       "listname" : "dsa", 
                     "__v" : 0 }, 
               { "solved" : false,  
                 "_id" : ObjectId("60f2cc1b275bbb30d8cb269d"), 
                "topic" : "linked list",
               "name" : "reverse list", 
                 "url" : "www.list.com",
                "listname" : "dsa",
                 "__v" : 0 } 
               ], 
"__v" : 2 
}

Answer №1

To remove keys from req.body that have empty values, follow these steps:

cleaned_body = {}
body_data = JSON.parse(req.body)

Object.keys(body_data).forEach(function (item) { 
  if (body_data[item]) {
    cleaned_body[item] = body_data[item]
 }})

After cleaning up the data, utilize cleaned_body within the $set operation.

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

Utilizing Pug for Passing Variables to JavaScript

I am working with a Pug view that displays a set of links to users. The user is already authenticated and their username and department are stored in session variables. I am able to pass these variables to the view using this code: res.render('landin ...

What was the reason for needing to employ `toObject()` in mongoose to determine if an object contains a certain property?

From what I understand, there is no .toObect() function in JavaScript, but it is used in mongoose to convert mongoose documents into objects so that JavaScript built-in functions can be used. I sometimes struggle with when to use it. There are instances w ...

Bootstrap.js has the ability to utilize nested objects for organizing and

As I work on enhancing a Combobox class I developed to complement Bootstrap 4, I am aiming to align the Javascript with the existing Bootstrap code. During this process, I came across a snippet of code in bootstrap.js while studying the Modal component: ...

Which design pattern does Bootstrap v4 utilize for handling click events?

Trying to decipher this code snippet: $(document).on( Event.CLICK_DATA_API, Selector.DISMISS, Alert._handleDismiss(new Alert()) ) This particular piece is related to the Alert component: https://github.com/twbs/bootstrap/blob/v4-dev/js/src/alert.js I a ...

Exploring the world of connectivity between Spring and MongoDB involving authentication

My current Spring configuration is set up to connect to MongoDB in the following way: <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg name="mongo" ref="mongo"/> <con ...

Sharing stickers with Discord.js version 13

I have encountered an issue while trying to forward messages sent to my bot via DM. Everything is functioning smoothly, except for sending stickers. Whenever I attempt to send a message with a sticker, an Error DiscordAPIError: Cannot use this sticker is ...

Inverted Scrolling Problem in Firefox

I am facing an issue with a script that inverts mouse movement for horizontal scrolling. It works fine in most browsers except Firefox. I could use some advice on how to troubleshoot this problem! $("body").mousewheel(function(event, delta) { ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Creating a template based on an object type in JavaScript with Angular: A step-by-step guide

I have a collection of objects, each with a property indicating its type. Here's an example: [ { "type" : "date", ... },{ "type" : "phone", ... },{ "type" : "boolean", ... } ] I'm ...

Tips for persisting nested arrays of objects data with Mongoose

Currently, I am transmitting data from an angular reactive form. Here is the UI image of the Angular reactive form: Angular reactive form UI image Additionally, here is the image showing the data being sent to the backend in the browser console: Data bein ...

Enhancing Form Validation with Vuejs 2

With vue-validator being prepared for Vuejs 2, what is the most effective method for implementing frontend validation? UPDATE I've come across a fantastic plugin called Vee Validate ...

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

Guide to dividing a string and structuring it into an array

I need help breaking apart these strings: var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.' var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.' to create an array like this: joh ...

Encountering a DatabaseError while attempting to reset a password using Djongo and Django with a MongoDB Atlas database

As I work on building a password reset link for a Django-powered website integrated with Djongo, I encounter an issue whenever I input a password and attempt to reset it - triggering the following error: Environment: Request Method: POST Request URL: htt ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

Is it possible to set up an automatic redirection to the Identity Provider sign-in page when accessing a protected page in Next.js using Auth.js?

Currently in the process of developing a web platform utilizing [email protected] and Auth.js([email protected]). The provider has been configured with the given code, allowing successful signing in using the "Sign in" button. auth.ts import Ne ...

The process of utilizing bsondump on a Windows operating system

Is there a way to utilize bsondump and its command in Windows? Every time I try to run bsondump foo.bson > foo.json I keep getting an error message saying: 'bsondump' is not recognized as an internal or external command, operable program or ...

The accordion seems to be stuck in the open position

Working on a website, I encountered a frustrating bug with an accordion feature. When clicking on the arrow, the accordion opens and closes smoothly. However, when attempting to close it by clicking on the title, the accordion bounces instead of closing p ...

Eliminating redundant subdocuments in MongoDB

This particular schema represents a single document out of thousands in the database, all housed within the same collection. Document 1: { pageNumber: 0, results: [ { jobkey: "AAA", }, { jobke ...

The video playback encountered an issue. Unable to access properties of undefined while attempting to play the video

I am facing an issue with my video gallery where I can't seem to play one video at a time. Instead, I keep getting this error message: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'play'). I suspect it may be ...