Updating only partial sections of a mongo object

I have a JSON document stored in MongoDB that has the following structure:

{
    "_id" : "cfqjJW8WZprDSJEop",
    "rName" : "z1",
    "pName" : "P-4",
    "ipAddress" : "21.1.1.12",
    "misc" : {
        "createdBy" : "admin",
        "updatedBy" : "admin",
        "creationTime" : ISODate("2016-09-15T09:43:10.953Z"),
        "updatedTime" : ISODate("2016-09-15T09:43:10.953Z")
    }
}

In my Meteor application, I have written code in the helper function to update only the updatedBy and updatedTime fields of this document during each update operation.

The misc object is dynamically added just before inserting or updating the record.

However, when I try to update the record using my code snippet below, the entire misc object gets replaced with the new values, causing the loss of createdBy and creationTime fields:

doc = // contains the updated document.
misc = {};
misc.updatedBy = //some name
misc.updatedTime = new Date();

doc.misc = misc,

r.update(id, doc); // calling Meteor's update method

I've also attempted to partially update the object by injecting something like this into the doc:

doc.$set.misc.updatedBy 

But it resulted in an error stating that updatedBy does not exist. Can anyone suggest the correct approach to partially update an object within a document?

Answer №1

Don't use doc.$set.misc.updatedBy

Try this instead:

doc = {
    "$set": {
        "misc.updatedBy": "new information"
    }
};

In this scenario, we are employing the MongoDB Dot Notation for accessing attributes within nested documents.


For instance:

var doc = {
    "$set": {
        "misc.updatedBy": "new information",
        "misc.updatedTime": new Date(),
    }
};

r.update(id, doc);

Answer №2

By default, when using the MongoDB update command, it will completely replace the document(s). However, if you only want to update a specific field and leave the other fields untouched in the matching documents, you can utilize the set operator in the MongoDB update command.

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

An error has been caught in the console stating that an undefined function is not recognized

Encountering a console error (Uncaught TypeError: undefined is not a function) on line 156 upon loading and unable to resolve it. Provided below is the line causing the issue along with its full context. Also included is the site link for reference. Any he ...

Argument typed with rest properties in Typescript objects

I'm relatively new to Typescript and have managed to add typings to about 90% of my codebase. However, I'm struggling with rest/spread operators. While going through our code today (which I didn't write), I came across this snippet that does ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

Remove all sub-items from the database when removing a parent item with MongoDB and Express

In my mongodb database, I manage three collections: clients, programs, and data. The data is nested within programs, and programs are nested within clients. This means that a single client can have multiple programs, and each program can contain various da ...

What is the best Document Object Model (DOM) to utilize alongside Spider

I want to incorporate the GoogleMaps JavaScript library into SpiderMonkey using the python wrapper, but the absence of a DOM is hindering my progress. Is there a method to inject a DOM into this setup in order to successfully make it function? ...

Why isn't the login redirect script working without any errors or redirection?

Struggling to develop a Greasemonkey script that can automatically fill in certain forms and then redirect to another URL once the form is submitted. // ==UserScript== // @name usersaime // @description fills data form for user and pass // @include h ...

Selecting values from req.body dynamically based on database attribute requirements

I am in the process of developing a Node/EJS/Mongo app where users are creating a capability survey and specifying the desired level for each question. The interface for selecting these levels consists of dropdown menus with options like: <select class ...

What is the best way to reduce the width of the navigation bar?

I've been working on creating a website for my friend, and I decided to include a table navigation bar to make it easier to navigate. Instead of duplicating the code, I separated the bar code into another file and used JavaScript to load it into each ...

Troubleshooting: The issue of Vue (v-on) not recognizing my function

I am brand new to Vue and JS, so please bear with me as I ask some "silly" questions. Within my Vue-Pet-Project, I have implemented a self-authored class module called Sudoku. In this module, I aim to find solutions using backtracking. Upon clicking the " ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...

I encountered a problem when attempting to execute my database

An error occurred with the connection string while trying to connect to MongoDB. Please check the path and try again. To fix this issue, review your connection settings in the code provided below: const mongoose=req ...

What is the best way to compare two sets of arrays and generate a new one with unique key-value pairs?

I have two arrays and I want to extract specific key-value pairs from each and combine them into a new array, handling duplicate entries. First Array : [ {id: 2, name: "HSBC", status: "YES"}, {id: 3, name: "Morgan Stanley&quo ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

I am struggling to understand how to make use of ajax and php to reload data for pagination

$(function(){ $('.page').click(function() { var paging = $(this).attr("name"); var dataString = 'page='+paging; $.ajax({ type: "POST", url: "<?php echo $backtrack; ?>shop.php", data: dataString, ...

Error encountered when utilizing sceneLoader to import a scene produced by the THREE.js Editor

An issue arises with the error message Uncaught TypeError: Cannot read property 'opacity' of undefined identified on three.js:12917 The current scene file in use is as follows: { "metadata": { "version": 4.3, "type": "Object", "gene ...

Express.js enables dynamic routing by leveraging request parameters

Currently, I am in the process of developing a RESTful API with expressJS. Within my controller, I have multiple functions such as Chall_1, Chall_2, and so on. exports.validateChall_1 = function(res) { //logic res.json(1); }; exports.validateChall_2 = f ...

Scrolling horizontally in vue-chartjs-chartwidget

I have a question regarding vue-chartjs. I am looking to achieve a similar result to the one demonstrated in this jsfiddle example: http://jsfiddle.net/mbhavfwm/ Below is the code for my Vue.js component (Chart data is passed through params). &l ...

Tips for integrating JavaScript code into React JS applications

I am attempting to create a scrollable table that scrolls both horizontally and vertically, using the example provided by . In my project directory under src/components/ScrollExample.js, I have copied and pasted the HTML code. In addition, in src/styles/c ...

Javascript encounters difficulty in converting timestamp to a date format

I am utilizing this particular function export const getDate = (stamp: string) => { console.log(stamp) //1581638400000 let date : any = Date.parse(stamp) console.log(date) //NaN let month = date.getMonth() let day = date.getDay() ...

Dnd-kit: item loses its place in line when dragged over Droppable area

I've encountered an issue while using @dnd-kit. The sorting function works smoothly (e.g. when I drag the 1st element, it sorts correctly), but once I reach a droppable element (green Thrash), the sorting breaks and the 1st element snaps back. You ca ...