Using Mongoose $addToSet to add items to an array only if they are unique

Currently, my code is set up to add new flagDtos using $addToSet without consideration for the uniqueness of item.name. However, I want to change this behavior so that:

  • If item.name is unique, add the new flagDtos object.
  • Otherwise, update the existing flagDto if it matches a item.name.

I am looking for a way to conditionally use $addToSet. Any suggestions on how to achieve this?

  async addFlagsToFeature(_id: number, flagDtos: FlagDto[]): Promise<FeatureResponse> {
    const filter: FilterQuery<FeatureDocument> = { _id };
    let success;
    var flagIds = [];

    return this.featureModel
      .findOneAndUpdate({ filter, $addToSet: { flags: flagDtos } })
      .then((doc) => {
        const featureDto = new FeatureDto();
        featureDto.mapFromSchema(doc);

        featureDto.flags.forEach((item) => {
          flagIds.push(new FlagDto({ featureFlagId: item.featureFlagId }));
          success = new SuccessFeatureResponseDto(featureDto.id, flagIds);
        });
        return new FeatureResponse(success, null);
      })
  }

Below is the structure of my FlagDto class:

export class FlagDto {
  featureFlagId?: string;
  name: string;
}

Answer №1

To optimize performance, it is recommended to use $addToSet with scalar values. In this scenario, you will need to execute two separate queries:

First, insert a subdocument using $push only if it does not already exist ($nin operator):

db.collection.update({
  < your filter conditions here >
  "flags.name": {
    $nin: [
      < the name extracted from FlagDto >
    ]
  }
},
{
  "$push": {
    "flags": < the data from FlagDto >
  }
})

Then, update the existing subdocuments (including the one inserted in the previous query) using $set:

db.collection.update({
  "flags.name": < the name extracted from FlagDto >
},
{
  "$set": {
    "flags.$": < the updated data from FlagDto >
  }
})

You can execute both queries sequentially (wait for the $push operation to complete before running the $set operation), or combine them into a single ordered bulk write operation for slightly improved efficiency.

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

Best practices for interacting with a REST API using Angular

I am currently working on a web Angular app where in globalservice.ts I have defined basepath:string = "https://myapi.com/api/v2/". I need to retrieve data from this API. To achieve this, I have included the following code snippet in server.js. Any recomme ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...

Despite the value being true, the if statement does not work when used with a Mongoose object in Node.js

Currently working on a bidding app, Below is the schema for the bidding model const bidSchema = new mongoose.Schema({ name: String, price : Number, description: String, location: String, specilization: String, image: String, ...

Exciting updates revealed upon new additions (angular)

I'm working with three components in my Angular application: app.component, post-create.component, and post-list.component. Let's take a look at the structure of these components: <app-header></app-header> <main> <app-post-c ...

Exploring the depths of mongodb through targeted field queries

I am working with a collection of objects structured like this : var Meetup = new Schema({ name: String, text:String, }); My goal is to retrieve all meetups whose name contains a specific string. Below is the API code snippet : module.exports. ...

Omit select dormant modules when building (Angular5)

Currently, I am collaborating on a project that is being implemented across various customer instances. Within the project, we have several lazy loaded modules, with most of them being utilized by all customers. However, there are certain modules that are ...

Consolidating Typescript modules into a single .js file

Recently, I was able to get my hands on a TypeScript library that I found on GitHub. As I started exploring it, I noticed that there were quite a few dependencies on other npm packages. This got me thinking - is there a way to compile all these files int ...

Has an official Typescript declaration file been created for fabric.js?

Currently, I have come across a Typescript definition for fabric.js on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fabric (https://www.npmjs.com/package/@types/fabric). However, its official status is unclear. Does anyone have more ...

The correct procedure for refreshing a page in Angular 8

Note: I found some code snippets online but, after testing them out, I have doubts about their reliability due to inconsistencies. In my script, I have developed two utility functions - one for moving to the parent node and another for reloading the curre ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

I encountered a TypeError when attempting to load MDX in Next.js with the mdx-js/react library

My Goals and Assumptions for the Project Please note that this question has been translated using Deepl Translations. I aim to integrate mdx-js/react into Next.js for loading mdx files. Environment Details: Operating System: macOS Big Sur Node Version: ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Is it possible to deactivate the error message related to "Unable to ascertain the module for component..."?

I recently incorporated a new component into my TypeScript2+Angular2+Ionic2 project. Right now, I have chosen not to reference it anywhere in the project until it is fully developed. However, there seems to be an error thrown by Angular/ngc stating "Cannot ...

Generate iframes dynamically in Angular Fire by retrieving data from a database query, dealing with the unsafe value using DOM Sanitization

Currently, I am using Ionic and Angular with Firebase to develop a daily readings application that dynamically displays an iframe for embedded YouTube videos based on the date. Everything works fine until I try to use data bindings in the source URL for th ...

What causes observables stream to be cancelled or stopped by my HTTP request?

I am facing an issue with adding a new property called Blobs to each application in an array of applications. I need to make a separate HTTP request to fetch Blobs for each application using the switchMap operator. However, the problem is that only the las ...

The Ins and Outs of Selecting the Correct Module to Attach a Controller in NestJS CLI

My experience with NestJS has been great so far, especially the Module system and how easy it is to parse requests. However, I have a question about the NestJS CLI. Let's say I have multiple modules. When I create a controller using the command "nes ...

Is it possible to compile a .ts file at the root level without following the tsconfig.json configurations?

After dealing with the challenge of having both .ts and .js files coexisting in each folder for months, I have finally managed to get the app to compile correctly. The transition from JS to TS brought about this inconvenience, but the overall benefits make ...

"Troubleshooting: Child Component Not Reflecting Changes in UI Despite Using Angular

My child component is designed to display a table based on a list provided through @Input(). The data is fetched via http, but the UI (child component) does not update unless I hover over the screen. I've seen suggestions about implementing ngOnChange ...