Is there a problem mixing javascript and typescript in node projects?

I am very new to node.js and typescript. I am trying to learn by porting an existing application over from python. I am getting a syntax error in a place I do not expect.

I have a class that is the workhorse of the project. It is in a file called myClass.ts

myProject
└── js
    ├── commands
    │   └── rules.js
    ├── myClass.ts
    └── main.js

rules.js includes myClass as:

try {
    const {myClass} = require("../myClass.ts")
} catch(e) {
    console.log(e)
}

I am using PyCharm and can put a breakpoint in the catch block. The error points to the constructor in the class. The error is:

/home/me/PycharmProjects/myProject/js/myClass.ts:44
        rule_type: string,
                ^

SyntaxError: Unexpected token ':'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/me/PycharmProjects/myProject/js/commands/rules.js:4:19)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

myClass is too big to fit in here. It starts:

const {randomInt} = require('crypto')

class myClass {
    constructor(
        rule_type: string,
        display_type: string,
        range_min: number     = 1,
        range_max: number     = 10000,
        display_mapping: {}   = undefined,
        value_adjustments: {} = undefined,
    ) {
        this.rule_type = die_type
        this.display_type = display_type
        this.range_min = Math.trunc(range_min)
        this.range_max = Math.trunc(range_max)
        this.display_mapping = display_mapping
        this.value_adjustments = value_adjustments
    }

    ...//a bunch of methods, etc
}

exports.myClass = myClass;

If I take the : string type hint away, then the error just falls down to the next type hint. Is there a problem mixing javascript and typescript in this way?

Why am I mixing js and ts? I found a sample node project that seems to be a reasonable starting point for what I want to do. I figured that trying out typescript for this class might be a good exercise.

** Edit **

Thanks to all. Much to learn…

Why am I getting a 500 when uploading file via the browser but not via Postman?

When I run my API on Postman, the file gets stored in S3 followed by the DB successfully, as depicted in the FileUploadController.php file below. I’m not sure if there’s something off in the Gallery.js file but my suspicion is that the name="userUpload" attribute on the <input/> isn’t being consumed properly by the POST request? But I’m not sure.

When I selected and upload a file on the browser, I get an error when I check the logs that says:

local.ERROR: Call to a member function getClientOriginalName() on null {"userId":1,"exception":"[object] (Error(code: 0): Call to a member function getClientOriginalName() on null at /var/www/app/Http/Controllers/FileUploadController.php:29)

I’m not sure why getClientOriginalName() gets null when trying on the browser but seems to work fine, all-around, when trying on Postman. console.log(data); displays the file name correctly, so we can rule that out in terms of it’s undefined or null.

How can I fix this?

Here’s FileUploadController.php file:

public function fileUpload(Request $request)
{

    $path = env('AWS_S3_PATH');
    $file = $request->file('userUpload');
    $imgName = $file->getClientOriginalName();
    $bucket = env('AWS_BUCKET');
    $region = env('AWS_REGION');
    $url = "https://{$bucket}.s3.{$region}.amazonaws.com{$path}{$imgName}";
    $userId = Auth::user()['UserID'];

    $file->storeAs(
        $path, // Folder
        $imgName, // Name of image
        's3' // Disk Name
    );

    $data = [
        'url' => $url,
        'UserID' => $userId,
        'isUploaded' => true,
        'timeStamp' => time(),
        'updated_at' => time()
    ];

    Upload::create($data);

    return $data;

}

Here’s Gallery.js file:

import React, { useState } from 'react';
import {Button, Image, Modal} from "react-bootstrap";

const Gallery = () => {

    const [filePreview, setFilePreview] = useState(null);

    const [selectedFile, setSelectedFile] = useState(null);

    const handleShow = () => setShow(true);

    const handleFileInput = (e) => {
        setFilePreview(URL.createObjectURL(e.target.files[0]));
        setSelectedFile(e.target.files[0]);
    }

    const uploadFile = () => {
        const data = {
            'userUpload': selectedFile
        }

        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        }

        console.log(data);

        axios.post('http://localhost:8005/api/file-upload', data, {headers})
            .then(resp => {
                console.log(resp);
            }).catch(error => {
            console.log(error);
        });

    }

    return (
        <form encType="multipart/form-data">
            <div className="fileUpload text-center">
                <input type="file" onChange={handleFileInput} name="userUpload" required/>
                <Button variant="primary" onClick={handleShow}>
                    Launch demo modal
                </Button>
            </div>

            <Modal show={show} onHide={handleClose}>
                <Modal.Body>
                    <Image fluid src={filePreview}/>
                </Modal.Body>
                <Modal.Footer>
                    <Button variant="primary" onClick={() => uploadFile()}>Upload!</Button>
                </Modal.Footer>
            </Modal>

        </form>
    );
}

export default Gallery;

making a post request inside mapDispatchToProps in react-redux

I’m trying to make a post request inside a function whenever i click on a button.
here is the code of the button

<Button onClick={handleClick}>Add to Cart</Button>

and here is the `handleClick funcion:

const handleClick = (event) => {

        event.preventDefault(); 
        props.postCart(itemData.product_name, itemData.product_price);
    }

and here i showcase the code of mapDispatchToProps function:

const mapDispatchToProps = dispatch => {

    return {

        postCart: (productName, productPrice) => dispatch(postAddToCart(productName, productPrice))
    }
}

finally the code of postAddToCart:

export const postAddToCart = (productName, productPrice) => {

    const email = sessionStorage.getItem('email');

    return (dispatch) => {

        dispatch(productName, productPrice);
        //REST API endpoint
        axios.post('http://localhost:8000/api/auth/add-to-cart', {

            email:email, 
            
        })
        .then(resp => {

            dispatch({

                type: actionTypes.ADDED_TO_CART, 
                status: resp.status
            });
        })

        .catch(resp => {

            dispatch({

                type: actionTypes.ADDED_TO_CART, 
                status: "FAILED"
            });
        })

    }

}

But whenever i click the button Add to cart i get the following error:

Error: Actions must be plain objects. Use custom middleware for async actions.
knowing that i’m using the redux-thunk middleware.

Can you please tell me what’s the problem and how can i fix it ? thank you ^^. if i missed something tell me in comments to add it ^^

CRUD operations using mongoose and express

I am creating an express app using mongoose with the intention of connecting this to React for the frontend.

I have listed some CRUD operations for a customer controller below but there are a few things I do not like about this approach.

  1. When using Customer.findById with a valid ObjectID that is not found, it returns null with a 200 response code. I want this to return 404 if no customer was found. I realise I could change the catch response to a 404, but I want to have some generic error handling incase the server goes down during the request or an invalid ObjectId was provided, which brings me to my next item.
  2. If I provide an invalid ObjectId I want to provide some meaningful message, is 500 the right response code?
  3. Error handling: Am I returning errors the correct way? currently errors return a string with the error message. Should I return JSON instead? e.g. res.status(500).json({error: error.message). I am planning on connecting this to react (which I am still learning) and I assume the UI will need to display these messages to the user?
  4. findById is repeated in getCustomerById, updateCustomer, and deleteCustomer. I feel this is bad practice and there must be a more streamlined approach?
  5. I want to have one function that validates if the ObjectId is valid. I am aware that I can do this is the routes using router.params but I’m not sure if checking for a valid id should be in the routes file as it seems like something the controller should be handling? See routes example below from another project I did.

What are the best practices and suggested ways to improve my code, based on the above?
I have read the documentation from mongoose, mozilla, and stackoverflow Q&A but they don’t seem to address these issues (at least I could not find it).

I am really after some guidance or validation that what I am doing is correct or wrong.

customer.controller.js

const Customer = require("../models/customer.model");

exports.getCustomers = async (req, res) => {
  try {
    const customers = await Customer.find();
    res.status(200).json(customers);
  } catch (error) {
    res.status(500).send(error.message);
  }
};

exports.getCustomerById = async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id);
    res.status(200).json(customer);
  } catch (error) {
    res.status(500).send(error.message);
  }
};

exports.addCustomer = async (req, res) => {
  try {
    const customer = new Customer(req.body);
    await customer.save().then(res.status(201).json(customer));
  } catch (error) {
    res.status(500).send(error.message);
  }
};

exports.updateCustomer = async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id);
    Object.assign(customer, req.body);
    customer.save();
    res.status(200).json(customer);
  } catch (error) {
    res.status(500).send(error.message);
  }
};

exports.deleteCustomer = async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id);
    await customer.remove();
    res.status(200).json(customer);
  } catch (error) {
    res.status(500).send(error.message);
  }
};

Router.params example
This is a routes file (not related to my current app) and is provided as an example of how I have used router.params in the past.

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const Artist = require("../models/Artist");
const loginRequired = require("../middleware/loginRequired");

const {
  getArtists,
  addArtist,
  getArtistById,
  updateArtist,
  deleteArtist,
} = require("../controllers/artistController");

router
  .route("/")
  .get(loginRequired, getArtists) // Get all artists
  .post(loginRequired, addArtist); // Create a new artist

router
  .route("/:id")
  .get(loginRequired, getArtistById) // Get an artist by their id
  .put(loginRequired, updateArtist) // Update an artist by their id
  .delete(loginRequired, deleteArtist); // Delete an artist by their id

router.param("id", async (req, res, next, id) => {
  // Check if the id is a valid Object Id
  if (mongoose.isValidObjectId(id)) {
    // Check to see if artist with valid id exists
    const artist = await Artist.findOne({ _id: id });
    if (!artist) res.status(400).json({ errors: "Artist not found" });

    res.locals.artist = artist;
    res.locals.artistId = id;

    next();
  } else {
    res.status(400).json({ errors: "not a valid object Id" });
  }
});

module.exports = router;

In node.js(); mongoose find() method works but dont give me value

I have an issue.

I should use mongoose find() method some queries. While using find() method, when i giving filter; find method() works but it doesnt give me value/values.

const messages = await MessageSchema.find({sessionId: sessionId}, {__v: 0, _id: 0, updatedAt: 0}).exec();

Above code is my find method. This code give me as value, empty array. []

But in this code,

const messages = await MessageSchema.find({}, {__v: 0, _id: 0, updatedAt: 0}).exec();

give me an array and all of messages is in the array.

But i should use filtering.

This is my message Schema.

const mongoose = require('mongoose');

var schema = new mongoose.Schema({
    participant_name: {type: String},
    message: {type: String},
    sessionId: {type: String},
    participantId: {type: Object}
}, {
    timestamps: true
});


module.exports = mongoose.model("Message", schema)

Could you help me pls.

Why are HTML tables I’m loading into TinyMCE corrupting themselves when all other content renders correctly?

I have a platform that allows individuals to create their own online forms. The structure of these forms are stored in a JSON format, and then this data is used to render the form to the end-user. When building a form, you have the option to use TinyMCE for textareas, to allow rich-text content.

Incomplete forms can be saved for future completion. In this instance, the JSON is again saved, but this time including an additional userData array which contains all the data that has been entered so far. When a user continues, this JSON is then reloaded, and fields are automatically populated with their existing data.

This all works fine. It also works fine for TinyMCE instances – except when it involves a table.

It’s somewhat hard to explain, so I have provided an example.

The following is a rendered form and I have inserted some data

Picture of generated form

The code used to generate (the empty) form is:

var formData = ‘[{“type”:”text”,”required”:false,”label”:”A Text Field”,”className”:”form-control”,”name”:”text-1640899516795″,”subtype”:”text”},{“type”:”textarea”,”subtype”:”tinymce”,”required”:false,”label”:”TinyMCE Text Area”,”className”:”form-control”,”name”:”textarea-1640638516810″}]’;

The TinyMCE element will show the following source code for the table I have entered:

<table style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<td style="width: 31.5117%;">header 1</td>
<td style="width: 31.5117%;">header 2</td>
<td style="width: 31.5138%;">header 3</td>
</tr>
<tr>
<td style="width: 31.5117%;">Entry 1</td>
<td style="width: 31.5117%;">Entry 2</td>
<td style="width: 31.5138%;">Entry 3</td>
</tr>
</tbody>
</table>

Now, if I save the form and reload, the form is populated with my data – except, as you will see, the table is messed up.

Corrupted table

The source displayed by TinyMCE is:

<table style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<td style="width: 31.5117%;">header 1</td>
<td>&nbsp;</td>
<td>Entry 31.5138%;"&gt;Entry 3</td>
</tr>
</tbody>
</table>

The JSON being used to generate the form looks like this:

var formData = ‘[{“type”:”text”,”required”:false,”label”:”A
Text
Field”,”className”:”form-control”,”name”:”text-1640899516795″,”subtype”:”text”,”userData”:[“whatever”]},{“type”:”textarea”,”subtype”:”tinymce”,”required”:false,”label”:”TinyMCE
Text
Area”,”className”:”form-control”,”name”:”textarea-1640638516810″,”userData”:[“<table
style=”border-collapse: collapse; width: 100%;”
border=”1″>rnrnrn<td style=”width:
31.5117%;”>header 1rn<td style=”width: 31.5117%;”>header 2rn<td style=”width: 31.5138%;”>header 3rnrnrn<td style=”width: 31.5117%;”>Entry 1rn<td style=”width:
31.5117%;”>Entry 2rn<td style=”width: 31.5138%;”>Entry 3rnrnrn”]}]’;

I’m working on the basis that something in the above is breaking the rendering, but I can’t work out what. Equally, this issue only seems to occur when using tables. You can go wild with formatting in TinyMCE and it will always render correctly after saving – unless you use a table.

I appreciate I’m using a lot of custom rendering here, but can anyone help me narrow down where things are going wrong?

How to make a button only visible under certain condition(the condition increase everytime one clicks the button?)

I am making a Javascript game, where I would like a button (class = “build”) to only be visible under certain conditions, and the condition would increase every time after one click the button.

To increase the number by 1, click the “gather” button. To make it more effective, click the “build” button to automatically increase the number by 0.1 per second. But I would like the “build” button to be only visible after the number reached 10. The “build” button would decrease the current number by 50% when one clicks it so that it would become invisible after being clicked.

The second time, the “build” button would only be visible when the number reached 12. Click it, the number decreases 50%, the “build” button disappears. The third time the button would become visible when the number reached 14 (so it’s +2 every time”), click it, the number decreases 50%, the “build” button disappears and it goes on and on.

Is there any way for this to work? I have some basic code down. Thanks!


let btn1 = document.querySelector(".btn1");
let btn2 = document.querySelector(".btn2");
let num = document.getElementById("num");
let increment = 0;

function toGather(){
num.innerHTML++;
}

btn1.addEventListener("click",toGather)

function toBuild() {
increment+=.1

if (increment == .1){
  setInterval(() => {
    num.innerHTML =parseFloat(parseInt((parseFloat(num.innerHTML)+.05+increment)*10)/10);
    
    
  }, 1000)} else num.innerHTML =parseFloat(parseInt((parseFloat(num.innerHTML)+.05+increment)*10)/10);
}

btn2.addEventListener("click",toBuild);

<span id="num">0</span>
<button class="btn1">Gather</button>
<button class="btn2">Build</button>

Javascript to Search In Multiple Tables in same page with multiple search bars

I found this previous thread, which is EXACTLY what I need but for some reason I can’t get it to work.
Javascript to Search In Multiple Tables in same page

I copied the code exactly from this jsfiddle (http://jsfiddle.net/690713m4/1/) to an entirely new page just to eliminate any bonehead errors I was potentially making and it still will not work like it does in the jsfiddle

Here is the code :

    <html>
    <script sec="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script srt="https://code.jquery.com/jquery-3.3.1.js"></script>
    <body><div class="input-group">
    <input class="form-control" id="search" type="text">
</div>

<table id="table" class="table paginated table-hover no-wrap">  
  <tr><td>PHP</td></tr>
  <tr><td>C#</td></tr>
  <tr><td>Javascript</td></tr>
  <tr><td>Jquery</td></tr>
  <tr><td>SQL</td></tr>
</table>
<br><br>

<div class="input-group">
    <input class="form-control" id="search2" type="text">
</div>
<table id="table2" class="table paginated table-hover no-wrap">  
  <tr><td>Bootstrap</td></tr>
  <tr><td>Java</td></tr>
  <tr><td>C++</td></tr>
  <tr><td>Pyton</td></tr>
  
<script>var $rows = $('#table tbody tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows.show().filter(function() {
    var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
    return !~text.indexOf(val);
  }).hide();
});

var $rows2 = $('#table2 tbody tr');
$('#search2').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows2.show().filter(function() {
    var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
    return !~text.indexOf(val);
  }).hide();
});</script>
</table>
</body>
</html>

Do I need to use await for async actions in react components?

I made this store:

export class CommentStore {
  comments = []

  constructor() {
    makeAutoObservable(this, {}, { autoBind: true });
  }

  async loadPostComments(postId: number): Promise<void> {
    const res = await API.loadPostComments(postId);
    runInAction(() => {
      this.comments = res;
    });
  }

  async sendComment(postId: number, comment: Comment): Promise<void> {
    try {
      await API.sendComment(postId, comment);
      await this.loadPostComments(postId);
      return true;
    } catch (err) {
      console.log('oops');
    }
  }
}

Do i need use await in react components? For example:

useEffect(() => {
      (async function () {
        await loadPostComments(postId);
      })();
    }, [loadPostComments, postId]);

But this also works fine:

useEffect(() => {
  loadPostComments(postId);
}, [loadPostComments, postId]);

Same for sendComment onClick:

onClick={()=>{sendComment(postId, comment)}}
onClick={async ()=>{await sendComment(postId, comment)}}

So, is it necessary to use await in this situations?

Text animation in contact form – HTML/CSS

I have the following code:

/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type="text"]:focus,
input[type="email"]:focus,
#subject:focus {
  background: var(--bgFormElsFocus);
  transform: scale(1.02);
  transition: transform 0.2s ease-in-out;
}

input[type=submit]:hover {
  opacity: 0.9;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

.shakingErr {
  border-color: red;
  animation: shake 0.82s forwards;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="https://formspree.io/f/xr123gjbqpq" id="my-form" method="POST" novalidate>
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>
            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

I would like a text animation on the input fields. For example, I would like my expected output to be like this:

https://watch.screencastify.com/v/3mlMie2rx0UzhdymHYCR

As you can see, I would like the text such as “First Name” to be inside the input field, and when the user clicks the input field, the text should animate and be at the top. How can I achieve this task? Any suggestions?

How can I animate an accelerating a DOM element with JavaScript?

I am making an application where I need a object to move from point a to point b starting out fast but then slowing down. I want to do this with pure vanilla js and no libraries whatsoever. This is my current code for animating something at a constant speed and I was wondering if it was possible to modify it or something.

let player = document.querySelector('.player');
var id = setInterval(frame, 1);
let counter = 0;
function frame() {
    if (counter == 50) {
        clearInterval(id);
                counter = 0;
        return;
    } else {
        player.style.top = player.offsetTop - 2 + 'px';
        counter++
    }
}

Ajax json doesnt show any instances

that even if i connected json data to ajax, it doesnt show me any results.

def get_json_categories(request):
    query_get = request.GET
    if query_get:
        query_get = query_get['q']
        categories = EcommerceProductCategory.objects.filter(name__contains=query_get).order_by('name')
    else:
        categories = EcommerceProductCategory.objects.order_by('name')

    data = {}
    data['results'] = []
    for category in categories:
        data_to_return = {}
        data_to_return['id'] = category.id
        data_to_return['name'] = category.name
        data['results'].append(data_to_return)

    return JsonResponse(data)

And i urled that to ecommerce/get_json_categories

and in the Django html

<div class="mt-2">
                <hr>
                <div class="form-group">
                    <select class="form-control w-30" name="category_select" id="category_select" aria-describedby="category_select" required></select>
                </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    $('#category_select').select2({
        placeholder: 'Wybierz kategorię',
        ajax: {
            url: 'http://127.0.0.1:8000/ecommerce/get_json_categories',
            dataType: 'json',
            data: function (params) {
                return {
                    q: params.term,
                    page: params.name
                };
            },
        }
    });
</script>

But it shows me “No results could be found” but that site (/ecommerce/get_json_categories) is full of json data.

How to group an array of objects in mongodb

im new to mongodb and Im having some trouble to group an array from a document like this:

_id: ObjectId('5d7afa2609d6ed000dffe1de')
email: "email@email.com"
transactions: [
    {
        "date": "2020-06-10T00:00:00.000+00:00",
        "shares": 100,
        "price": 20,
        "type": "buy",
        "equity_id": "petr4"
    },
    {
        "date": "2020-07-10T00:00:00.000+00:00",
        "shares": 200,
        "price": 10,
        "type": "sell",
        "equity_id": "petr4"
    },
    {
        "date": "2020-06-10T00:00:00.000+00:00",
        "shares": 250,
        "price": 30,
        "type": "buy",
        "equity_id": "vale3"
    }, ...
]

I would like to group these transactions by date and obtain an document like this:

_id: ObjectId('5d7afa2609d6ed000dffe1de')
email: "email@email.com"
transactionsByDay: {
    "2020-06-10": [
        {
            "shares": 100,
            "price": 20,
            "type": "buy",
            "equity_id": "petr4"
        },
        {
            "shares": 250,
            "price": 30,
            "type": "buy",
            "equity_id": "petr4"
        }
    ],
    "2020-07-10": [
        {
            "shares": 200,
            "price": 10,
            "type": "sell",
            "equity_id": "petr4"
        }
    ], ...
}

I tried an aggregation using a group operator but the result didn’t came as expected. Can someone give me a help to solve this?

Vis.js How to show only children/descendents of selected node?

If not posible with vis.js, I could do the entire thing on something else. But this functionality is crucial. So, show everything if nothing selected; show only children (with the “from” arrow) of some node if that node is selected. Or to select the node in some list, or type it somewhere.
https://codepen.io/andre-fr-silva/pen/ZEBPpqK

var container = document.getElementById("mynetwork");
var data = {
  nodes: nodes,
  edges: edges,
};