What is the best way to swap out the outdated schemas for the updated ones?

Hello there! I have some schemas set up like this:

{ user: '123', code: 'abc', uses: [...] },
{ user: '123', code: 'def', uses: [...] },

and my goal is to transform them into this format:

{ user: '123', code: ['abc', 'def'], uses: [...] },

I've been experimenting with the following query:

schema.aggregate([
    { $unwind: '$uses' },
    { $group: { _id: '$_id', user: { $first: '$user' }, code: { $addToSet: '$code' }, uses: { $addToSet: '$uses' } } }
  ]);

However, I'm not getting the desired result. While the 'code' field has become an array, it only contains one code.

I recently updated a function and now need 'code' to be an array instead of a single value. With over 400 documents, I want to update them all to fit the new function without manual intervention.

UPDATE: After making some adjustments, it seems to be working with:

{ $unwind: '$uses' },
{ $group: { _id: '$user', code: { $addToSet: '$code' }, uses: { $addToSet: '$uses' } } }

The issue (I believe) was with user: { $first: '$user' }, as removing it led to the expected outcome. Now the challenge is figuring out how to replace the old schemas with the updated ones.

Answer №1

This is the updated code that is now functioning correctly:

const invitations = await schema.aggregate([
    { $unwind: '$uses' },
    { $group: { _id: '$user', code: { $addToSet: '$code' }, uses: { $addToSet: '$uses' } } }
]);

for (const invitation of invitations) {
    await schema.deleteMany(
      {
        user: invitation._id
      }
    );
    
    await new schema(
      {
        user: invitation._id,
        code: invitation.code,
        uses: invitation.uses
      }
    ).save();
};

In my previous edit, I mentioned that the issue was with user: { $first: '$user' }, but the reason behind this error remains unclear to me.

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

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

A step-by-step guide on extracting values from JSON using JavaScript

I am facing a challenge in extracting values from a JSON string. The JSON string I have is: {"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

What is the best way to utilize the constructor in a JavaScript object so that only the properties within `this` are utilized?

I am looking to instantiate the following class: class Person { firstName; lastName; birthday; constructor(props: Person) { {firstName, lastName, birthday} = props } } var me = new Person({firstName: "donald", lastName: "trum ...

Assemblage of Marionettes: Adding multiple elements to the DOM

I am working on a Marionette application and have come across an issue with inserting new tab items. I have a collection of tabs, but when adding a new item, I need to insert DOM elements in two different areas. The problem is that Marionette.CollectionV ...

The close button on the jQuery UI Dialog fails to appear when using a local jQuery file

I may sound silly asking this, but I have a simple webpage where I've added a jQuery modal dialog box. Strangely, when I link directly to the jQuery files online (like http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css), everything works ...

Encountering a TypeError stating that the "option is undefined" error has occurred

Unexpectedly, my dropdown menu that was functioning perfectly fine is now throwing an error. I've made several changes and none of them seem to resolve the issue. Could it be a data type mismatch or am I missing something crucial here? Your insights ...

Creating a fixed navigation bar for an ecommerce website

Recently, I purchased a webshop and I am trying to implement a sticky header that remains at the top of the page all the time. Unfortunately, none of the solutions I've tried seem to be working, and I'm stuck on how to proceed. Is there anyone ou ...

Struggling with iterating over an Angular array?

I am attempting to iterate through this array. However, I am not seeing anything inside the {{repeat.title}} I am iterating through the array using the following HTML/Angular code: <div class="column inline inline-4 center choice" ng-repeat="repeat i ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

I love the flexibility that webpack provides when it comes to using aliases to override existing dependencies in the node_modules folder

When using Webpack 4, I'm looking to replace the rsg-components from node_modules with my own version. By doing this, react-styleguidist should then import my customized component instead. It seems that resolve.alias doesn't have priority over ...

Creating a customizable triangle design using the power of three.js

Recently, I came across the three.js library and I'm eager to incorporate it into my projects. One idea I have is to create a 2D triangle shape with hand holds on the vertices which allow me to adjust the shape in real-time. Can anyone provide guidanc ...

Guide to creating seamless integration between AngularJS routing and ExpressJS routing when using html5mode

Yesterday, I posted a question on stackoverflow about my webpage's CSS and JavaScript not including after a refresh. I discovered that it was caused by html5mode, but I have been searching for a solution since then with no luck getting an answer. My ...

Utilize MongoDB reference IDs in Laravel application with the help of Jenssegers' library

Looking for a way to retrieve data from model A that is referenced in model B using an array ID. Here's my model A object: { "_id": "62eb2f788345c04a74057903", "location": "usa" } And here's my m ...

Enhance your JQuery skills by implementing variables within the .css() function

Attempting to randomly assign values to an image's left and right properties using JQuery. Here is the code snippet: var sides = ["left", "right"] var currentSide = sides[Math.floor(Math.random() * sides.length)]; $("#"+currentImage).css({currentSide ...

The infinite scrolling feature encounters issues when scrolling downwards

My infinite scroll code is causing a problem - it only works when scrolling up, not down. Can someone help me fix this issue? <script type="text/javascript"> $(document).ready(function(){ $(window).scroll(function(){ var lastID = $(&apos ...

Creating a Node.js Express application paired with a React.js frontend

In my application, I'm utilizing reactjs as the front-end technology and plan to use nodejs for server-side programming. After setting up the reactjs application, which generated project structure and package.json, I proceeded to install express, wit ...

Switch between dropdowns with jQuery

Issue at Hand: In the scenario illustrated below, there is a side navigation bar containing options that reveal a toggled section upon clicking. Specifically, if you select the third item labeled "Dolar" from the menu, a dropdown with three additional cho ...

``Is there a way to effectively assess the Angular UI-Grid cellTemplate function in the attribute value only when it is displayed

Utilizing angularjs and ui-grid with a custom cellTemplate, each cell contains an object referred to as COL_FIELD. This object is passed to a function that generates an image data URI used in the src attribute of the cellTemplate to display images within e ...