Upgrading embedded data in MongoDB using Mongoose

I have been attempting to modify the nested value data1 within a MongoDB document:

{
  "content": {
    "data": {
      "data1": "Some data",
      "data2": "Better data"
    },
    "location": {
      "coordinates": [
        45,
        45
      ],
      "type": "Point"
    }
  },
  "_id": "647e40c590bc322763bdf182",
  "title": "test",
  "description": "Here is some updated description",
  "tags": [
    "test",
    "pic",
    "newTag"
  ],
  "dataType": "NOTREFERENCED",
  "createdAt": "2023-06-05T20:08:37.345Z",
  "updatedAt": "2023-06-07T18:37:23.134Z",
  "__v": 0
}

Nevertheless, I am unable to achieve this. I am utilizing mongoose and have experimented with the subsequent approaches:

const id = "647e40c590bc322763bdf182"

await this.model.findByIdAndUpdate(id,{ $set: {content.data.data1: "Updated value"}},{new: true,});

await this.model.findByIdAndUpdate(id,{ content.data.data1: "Updated value"},{new: true,});

Answer №1

If you're looking to update an item in your database, you could consider the following code snippets:

import mongoose from 'mongoose';
import YourModel from './models/yourModel';

const id = "647e40c590bc322763bdf182";

const updateItem = async () => {
  try {
    const item = await YourModel.findById(id);

    if (!item) {
      const newItem = new YourModel({
        // ...
      });
      await newItem.save();
      return;
    }

    item.content.data.data1 = "Updated value";
    await item.save();
  } catch (error) {
    console.error("An error occurred:", error);
  }
};

updateItem();

Another approach you could take is using the findOneAndUpdate method as shown below:

import mongoose from 'mongoose';
import YourModel from './models/yourModel';

const id = "647e40c590bc322763bdf182";

const updateItem = async () => {
  try {
    const updatedItem = await YourModel.findOneAndUpdate(
      { _id: id },
      { $set: { 'content.data.data1': 'Updated value' } },
      { new: true, upsert: true }
    );

    console.log("Item updated:", updatedItem);
  } catch (error) {
    console.error("An error occurred:", error);
  }
};

updateItem();

Feel free to test out both methods and see which one works best for your situation.

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

$.ajax and $.getJSON are proving to be ineffective in retrieving responses from a 3rd party server when dealing with json and jsonp formats

I am currently working on retrieving a JSON response from an API provided by the website. I have experimented with different methods and received mixed results. My goal is to successfully retrieve and parse the JSON data to extract the specific information ...

Converting HTML code to JSON using PHP scripting

Would appreciate your help in resolving a small issue. Although I came across this post, I am still encountering some errors: How can I convert HTML to JSON using PHP? I have created a PHP file that extracts a post from WordPress with the following forma ...

415 Unsupported Media Type Error Encountered (JAVA with Angular Using RestFULL JSON)

I am encountering an issue with one of my controllers. When I attempt to send data from Angular to a Java controller using JSON content type, I receive an error as described in the topic above. As a result, I am unable to retrieve the response from the ser ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...

Unable to store loop information fetched from api into a JSON file

I'm currently facing an issue with my code where I am trying to save the results from looping through an API into a JSON file using writeFileSync. Here is the code snippet in question: function processRarity(limit) { var resultJson = []; for ( ...

Encountering the error code 413 Request Entity Too Large when utilizing the Croppic plugin

Utilizing the jquery plugin CROPPIC in my web application has been beneficial for cropping and compressing images before they are uploaded to the database. However, I have encountered a problem where images larger than 1MB result in an error in the conso ...

Having trouble with Canvas installation in NodeJS

Encountering an error after running npm install canvas and attempting to use it with: const canvas = require('canvas') npm ERR! code 1 npm ERR! path C:\Users\josep\OneDrive\Desktop\Bots\Foundation\node_m ...

Is there a Spring MongoDB annotation available specifically for creating a 2dsphere index on a geospatial field in Java development?

@JsonSerialize @Document(collection = "fence") @CompoundIndexes({ @CompoundIndex(name = "loc_groupId_idx", def = "{ 'loc': 2dsphere, 'groups.groupId': 1 }", unique = false) }) ...

Save my Facebook profile picture to my website folder

Retrieve a Facebook profile image and store it in my designated directory, "www.site.com/images". <?php $url = "https://graph.facebook.com/$id/picture?width=350&height=500&redirect=false"; ?> The value of "$id" is obtained from a textfield. ...

How to delete an element from a nested object array in MongoDB using Spring Criteria?

Currently in my SpringBoot 1.3.2 project, I am utilizing org.springframework.data.mongodb.core.query.* My goal is to remove an element from a nested object array. Within my main object, there is an array structured like this: "sections" : [ { ...

"Utilize Typescript to dynamically check data types during runtime and receive alerts for any potential

INTRODUCTION I am currently working with Angular 6. In Angular, typescript is utilized to allow you to specify the data type of your function's arguments: public fun1(aaa: number) { console.log(aaa); } If I attempt to call fun1 with a parameter ...

Tips for quickly applying a masked array to an extremely large JSON dataset

Data Analysis Challenge Currently, I am faced with the task of working on extensive JSON files that are structured as follows: {key: [1000+ * arrays of length 241], key2: [1000+ * arrays of length 241], (...repeat 5-8 times...)} The data is organized ...

Sorting the array in MongoDB before slicing it

Currently, I have a pipeline that aggregates Regions along with their respective countries and sales values. My goal is to obtain the top 5 countries by sales in each region using the $slice method. However, the issue I am facing is that it returns the fir ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

What is the best method for preserving my outcome as an indexed array?

I currently have an empty array called cust, but the JSON data (with some metadata) has been successfully loaded, as I can see in the Chrome debugger network preview. How can I populate my array with the results so that they are indexed and accessible in ...

Encountering issue while converting XML to JSON on Android platform

Attempting to retrieve data from the Earthquake API. Utilizing Retrofit for this task, fetching data in XML format and successfully converting it to JSON using an XML-JSON Converter Library. The library functions correctly with simple XML strings like: & ...

Facing issues with implementing a JSON file within an Android app developed with Ionic framework

I am facing an issue with my Ionic framework developed Android app. The simple JSON file is not working within the app. The application works fine in a local browser, but when I run it on my mobile device, the app is not able to fetch the JSON file using $ ...

Empty Object Morphia: Leveraging MongoDB

I am facing an issue with saving and retrieving data in MongoDB using Morphia. I have two simple POJO's named Company and Employee, where Employee is a referenced document in Company class. Although I am able to successfully save the Company Object, I ...

Can you inherit a type based on the keyof template in TypeScript?

I attempted a small hack to explore how DOM ts files map different element names to their types. My experiment involved trying to have a type MyType extend a different set of fields depending on the value of a string. Here is what I tried: interface Messa ...