"Utilizing mongoDb's $set and $setOnInsert directives for updating specific fields within nested properties

I have a file containing sub-categories

{
  a: fire,
  b: {
    plane: fly,
    c: swim,
    d: jump,
  }
}

During upserts, I want to specifically change the "plane" category.

Here is what I have attempted:

const { categories, ...rest } = newRecord;
const updateCategories = categories;
delete updateCategories?.plane;
await Model.findOneAndUpdate(
{
  id: newRecord.id,
},
{
  $set: {
    ...rest,
    categories: updateCategories,
  },
  $setOnInsert: {
    "categories.plane": newRecord.plane,
  },
},
{
  upsert: true,
});

The error message I keep encountering is: Unable to update both categories and categories simultaneously. Even though I am removing the plane entry from the data being updated, referencing it through the categories field seems to cause confusion.

How can I rephrase this so that mongo understands my intention to only impact the "plane" sub-category within the categories, not the entire categories field in the $setOnInsert? Is there a way to indicate that an insert operation is taking place in the $set block for adding a conditional statement?

EDIT: It should be noted that I am utilizing documentDb on aws, which is believed to be built on mongo 4.0.

Answer №1

After much searching, I finally found the solution detailed here on GitHub. The recommendation is to use the dotify function to handle certain scenarios.

export function dotify(obj: object) {
  const res: any = {};

  function recurse(obj: any, current?: string) {
    for (const key in obj) {
      const value = obj[key];
      const newKey = current ? current + "." + key : key;
      if (value && typeof value === "object" && !Array.isArray(value)) {
        recurse(value, newKey);
      } else {
        res[newKey] = value;
      }
    }
  }

  recurse(obj);
  return res;
}

  const { subproperties, ...rest } = newRecord;
  const updateProperties = subproperties;
  delete updateProperties?.aplus;
  await Model.findOneAndUpdate(
    {
      id: newRecord.id,
    },
    {
      $set: dotify({
        ...rest,
        subproperties: updateProperties,
      }),
      $setOnInsert: {
        "subproperties.aplus": newRecord.a,
      },
    },
    {
      upsert: true,
    }
  );

It appears that regular fields, including objects, are handled correctly when dotified. However, there seems to be an issue with how mongoose handles dotified arrays - they end up as undefined. This could possibly be related to schema configurations or limitations of the version of documentDb being used in AWS, which is based on an older version of MongoDB. It's worth checking if this has been addressed in newer versions.

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

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

Is it secure to disclose the _id of a document in publication?

Can anyone offer guidance on the safety considerations of publishing the _id of a document? I am currently utilizing an analytics tool to monitor user behaviors, and I find it necessary to retrieve the _id on the client side to enhance context. Neverthele ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

How can I apply conditions to the second element of a Number array with two elements in MongoDB?

My expertise lies in postgresql and relational databases, but I am open to exploring the possibilities of using mongo for certain purposes. Recently, I came across a website with exercises related to MongoDB . The exercises involve working with a document ...

I'm attempting to link up mongoDB with node.js, however I'm encountering an error in the terminal that says: "MongoAPIError: URI must contain hostname, domain name, and tld"

Currently facing an issue while attempting to establish a connection between MongoDB and node.js. The terminal is displaying the error message: MongoAPIError: URI must include hostname, domain name, and tld Backend Code I have implemented MongoDB code in ...

The mistake occurs when attempting to access a class property generated by a class constructor, resulting in a type error due to reading properties of

I'm having trouble building an Express API in TypeScript using Node.js. I am new to Express and I have been learning Node, JavaScript, and TypeScript since 2022, so I apologize if the question is not too complex. The issue I'm facing is trying to ...

Issue with detecting undefined in a nested function using Typescript

Examining the code snippet provided below, focus on the test getter. Why is it that const name = this.person.name does not result in an error, while const processPerson = () => this.person.name does generate an error? interface Person { name: string; ...

Locate duplicate entries that are not null in MongoDB

Currently, I am working on a deduplication script in MongoDB to identify duplicate mobile numbers that are either null or empty strings. I have experimented with the $ne operator in MongoDB without success. Can someone guide me on how to retrieve duplicate ...

Tips for having tsc Resolve Absolute Paths in Module Imports with baseUrl Setting

In a typescript project, imagine the following organizational structure: | package.json | tsconfig.json | \---src | app.ts | \---foobar Foo.ts Bar.ts The tsconfig.json file is set up t ...

Discovering an element in an Array using Angular 2 and TypeScript

In my setup, I have a Component and a Service: Component: export class WebUserProfileViewComponent { persons: Person []; personId: number; constructor( params: RouteParams, private personService: PersonService) { ...

Executing double UpdateMany operations in MongoDB using $inc

After receiving valuable assistance with my previous inquiry (UpdateMany mongodb documents with value from document), I have grasped the concept of incrementing using updateMany. The code I have crafted is as follows: ageAllCameraPriorities = async (req, r ...

Is it possible for RouteData in Angular 2 to transmit variables from a parent component to routed components?

How can I pass a variable from my AppComponent to CoursesComponent using RouteConfig? The "data" property in route config seems to only accept constant parameters and cannot recognize "this". Is there a workaround for this limitation? If not, what is the ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

How can I disable Typescript errors in VSCode for .JS / .JSX files while still keeping them for .TS / .TSX files?

Utilizing both typescript and plain javascript can be tricky. Some files are in JavaScript (.js) format, while others are in TypeScript (.ts) format. Despite this setup, I am encountering Typescript Errors & Warnings with my eslint in VSCode, even whe ...

Issue: property is not accessible on the current object in Angular 5

When trying to access a property from the object, I encountered an error. The JSON format received from the server is as follows: { "result": false, "messages": "welcome", "data": [ { "name": "siva", "category": true, "count": ...

gulp-angular2 task is malfunctioning

Currently, I am in the process of working on a gulpfile and have written the following task: var tsProject = ts.createProject('app/Resources/public/angular/tsconfig.json'); gulp.task('angular-2', function () { var tsResul ...

Can you provide guidance on searching in mongoose using both $and and $or conditions?

Script: const query = req.body.data; if(query!==''){ await User.find( { $or:[ {username: { "$regex": query, "$options": 'i' }}, {name: { "$regex": ...

Issue with ngAnimate in Angular 1.4 + TypeScript not functioning correctly upon initial page load

In Summary At the start, the view fades in when using ES5 (ES5 Example) The view does NOT fade in when utilizing Typescript import (Typescript and ES6 Import Example) I am currently exploring Typescript, ES6 modules, and their integration. Most aspects ...

Encountering an issue with Nuxt 3.5.1 during the build process: "ERROR Cannot read properties of undefined (reading 'sys') (x4)"

I am currently working on an application built with Nuxt version 3.5.1. Here is a snippet of the script code: <script lang="ts" setup> import { IProduct } from './types'; const p = defineProps<IProduct>(); < ...