Updating fields in MongoDB using dot notation

In my Mongo Schema, I have defined the following structure:

var OrderSchema = new Schema({
    postcode: String,
    ...
    status: {
        last_check: { type: Date },
        date: Date,
        code: String,
        postnum: String,
        text: String,
        class: String
    },
});

I am using a function to save data (the old method is commented out):

function save_order(data) {
//    var order = new Order(data);
//    var upsertData = order.toObject();
//    delete upsertData._id;
//    Order.findOneAndUpdate({postcode: order.postcode}, upsertData, {upsert: true}, function (err) {
  Order.update({postcode: data.postcode}, {$set:data}, function (err) {
    if (err) console.log('err');
  });
}

An example of data passed to the function is shown below:

{ postcode: 'BV123456789BY',
  status: 
   { last_check: 1413539153572,
     code: '06',
     postnum: '247431',
     date: Thu Oct 16 2014 09:52:00 GMT+0300 (Восточная Европа (лето)),
     text: '06. Поступило в участок обработки почты (247431) Светлогорск - 1' } }

The function to set status.class works well and does not overwrite the existing status values:

function setByOrderId(id, data) {
//   data = {'status.class': 'danger'}
    Order.update({_id: id}, {$set: data}, function (err) {
        if (err) console.log('err');
    });
}

However, the problem arises when updating the status as the value of status.class disappears. How can I update the status without overwriting status.code? Thank you.

Answer №1

Indeed, the solution provided fulfills the task at hand by avoiding overwriting existing properties. Despite the mention of "dot notation" in the title, it is not utilized in this particular scenario. The suggested approach effectively handles the objective without necessitating the use of "dot notation". Implementing the modification outlined ensures the preservation of current data while updating as required.

To resolve the issue, the initial step involves manipulating the data object using the following method:

var newobj = {};
Object.keys( data ).forEach(function(key) {
    if ( typeof(data[key]) == "object" ) {
       Object.keys( data[key] ).forEach(function(subkey) {
           newobj[key + "." + subkey] = data[key][subkey];
       });
    } else {
       newobj[key] = data[key];
    }
});

This results in a structured output within the newobj variable, facilitating subsequent updates seamlessly.

{
    "postcode" : "BV123456789BY",
    "status.last_check" : 1413539153572,
    "status.code" : "06",
    "status.postnum" : "247431",
    "status.date" : ISODate("2014-10-17T11:28:20.540Z"),
    "status.text" : "06. Поступило в участок обработки почты (247431) Светлогорск - 1"
}

Following this preparation, the standard update operation can be executed efficiently:

Order.update({ "postcode": newobj.postcode}, { "$set": newobj }, function (err) {
    if (err) console.log(err);
});

While additional recursion may be necessary for deeper nesting structures, the fundamental concept illustrated here should serve as a solid foundation for utilizing dot notation effectively in similar situations.

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

Arranging data in a JSON array while handling null values in JavaScript

Here is my JSON array: var jData = [ {id: 1, parent: null}, {id: 2, parent: null}, {id: 3, parent: 1}, {id: 4, parent: 2}, {id: 5, parent: 2}, {id: 6, parent: 1}]; I would like to sort it in the following order (first by id then by parent): [ {id: 1 ...

Experiencing memory issues while attempting to slice an extensive buffer in Node.js

Seeking a solution for efficiently processing a very large base64 encoded string by reading it into a byte (Uint8) array, splitting the array into chunks of a specified size, and then encoding those chunks separately. The current function in use works but ...

Surprising results from combining ng-mousedown with ng-click

I am working with the following HTML structure: <label ng-mousedown="mousedownHandler($event)" ng-click="clickHandler($event)"> <input type="checkbox" /> </label> Within my scope, I have the following methods defined: $scope ...

I desire to incorporate a subtle fading effect into the script

I have written the script code and now I am looking to add a fade effect to it. Can anyone guide me on how to achieve this? Your help is much appreciated! ※I used an online translator as English is not my native language. Please bear with any awkward ph ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Display a vibrant welcome screen on an Android WebView that ensures a visually appealing experience while the content loads for the

When launching an application, the desired behavior is as follows: Display a splash screen while simultaneously loading a URL Upon the firing of a JavaScript interface event on page load, remove the splash screen Mainactivity.java myWebView.addJavascript ...

What is the best way to narrow down the content cards displayed on the page?

I have recently developed a blog post featuring three distinct categories: digital marketing, tips and advice, and cryptocurrency. My goal is to implement a filtering system for these categories. For instance, I would like users to be able to click on a b ...

Struggle with connecting to Firebase database

I've been grappling with errors while trying to build a list of users using Firebase's collection feature. https://i.sstatic.net/BTPMM.png I've provided the information I'm inputting below: https://i.sstatic.net/yVD0i.png This is my ...

A Vue component library devoid of bundled dependencies or the need for compiling SCSS files

My current challenge involves the task of finding a way to publish our team's component library. These components are intended to be used by various internal applications within our organization. I have specific requirements: The library must be acc ...

access the data in the fresh window.open

I created a brand new window var win = window.open("", "", "width=400, height=200"); and now I want to access its body using var $windowBody = $(win.document.body); and then use functions like .find() and .html() While this method works smoothly on Fi ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Distinguishing $(document).width() and $("html").width() in jQuery on Internet Explorer 11

There seems to be an issue with IE11... APPROXIMATED (I presume...) console.log($(document).width()); // 808px; EXACT VALUE console.log($("html")[0].getBoundingClientRect().width); // 807.30993px; ROUNDED DOWN (or to the nearest whole number) console ...

What steps should I take to address both the issue of duplicate names and the malfunctioning fixtures?

There are issues with duplicate item names and the cache not updating immediately after running the script. Instead of fetching new data, it retrieves previous values from the last item shop sections. If the remove_duplicates function is not used, it displ ...

Encountered an error while trying to install @material-ui/core through npm: Received an unexpected end of JSON input

npm install @material-ui/core npm ERR! Unexpected end of JSON input while parsing near '...X1F+dSMvv9bUwJSg+lOUX' npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\WR-022\AppData\Roaming\npm-cach ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

Having trouble accessing and setting the values of a JSON array retrieved using $.get method in JavaScript outside of the function

Executing the following code snippet results in the desired values being displayed in console.log: var q; $.get('/ajax_subscribers', { code: 'qyhskkcnd'}, function(returnedData){ q = returne ...

Saving an item using localStorage

I've been struggling to figure out how to make localStorage save the clicks variable even after refreshing the browser. Initially, I attempted using JSON.stringify and JSON.parse but later discovered that using parseInt could be a more suitable optio ...

datetimepicker in bootstrap 5 experiencing issues

Recently, I delved into the world of JS and attempted to implement a datetimepicker in my web-demo. Everything was running smoothly with bootstrap 3.3.7, but as soon as I upgraded to version 5, the calendar disappeared. Below is the minimal working html c ...

Issue encountered while retrieving values from JSON for the data table

I recently developed an application using a combination of React and Flask to display JSON data in a table format. While I can successfully see the data loaded in the console, I encountered difficulties in rendering it within the data table. The technologi ...

Application utilizing the MEAN stack to interact with an API

After setting up the new mean app, I wanted to incorporate an API within the application. To achieve this, I made modifications in the server.js file by adding the necessary configurations like app.use and body parser to handle JSON data. Additionally, I i ...