Getting “undefined is not an object” on a validated array

I’m trying to access an array inside of an object that comes in a response:

getMatches().then((matches) =>{
let possibleDraws = []
console.log(matches)
console.log(typeof matches)
matches.forEach(match => {
    if(isPossibleDraw(match)){
        possibleDraws.push(match)
    }
    console.log(match.homeForm)    
}) 
console.log(possibleDraws)}).catch((err) =>{
console.log(err)})

console.log(matches) returns correctly an array with just one value for testing purposes:

0:
awayForm: (4) ['L', 'D', 'W', 'D']
awayTeamID: 15994
awayTeamName: "Maritzburg United U23"
homeForm: (4) ['L', 'D', 'W', 'D']
homeTeamID: 15990
homeTeamName: "Chippa United U23"
leagueID: 734
matchID: 793855
season: 2021
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)

However, when accessing match.homeForm, it returns “Undefined is not an object”, even when match.homeForm does exist (based on the last console.log) . I even mocked the response of getMatches() to the same array (original function calls an API and get the response as a promise) and it works perfectly fine, so I really have no idea what could be happening here.

How to provide type hints using JSDoc and Apollo Client?

I have trouble setting up type hints using JSDoc for my JavaScript code (trying to make this work with VSCode and WebStorm).

As first step, I converted GraphQL schema into set of JSDoc @typedef entries using @graphql-codegen/cli. For the sake of this converations, lets talk about this one specific:

// schema.js

/**
 * @typedef {Object} Country
 * @property {string} code
 * @property {string} name
 */

Then, somewhere in my App.js I tried writing:

// App.js

const GET_COUNTRIES = gql`
  query GetCountries {
    countries {
      code
      name
    }
  }
`;

/**
 * @typedef {import("./schema").Country} Country
 * @typedef {import("@apollo/client").QueryResult} QueryResult

 * @returns {QueryResult<Country>}
 */
const useGetCountries = () => {
  return useQuery(GET_COUNTRIES);
};

However, it looks like the type definitions from schema.js are being ignored (both App.js and schema.js are in the same directory).

My question is: is it possible to setup something like this – have IDE pickup JSDoc type definitions and provide type hints? If the answer is YES, how would I go around settings this up?

I’ve created a simple repro on CodeSandbox at https://codesandbox.io/s/graphql-type-hints-n1vh0

CoreMongooseArray(0) bug instead of Normal array

This is my index.js file

const mongoose = require('mongoose');

const Dishes = require('./models/dishes');

const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url);

connect.then((db) => {

console.log('Connected correctly to server');

Dishes.create({
    name: 'Uthappizza',
    description: 'test'
})
.then((dish) => {
    console.log(dish);

    return Dishes.findByIdAndUpdate(dish._id, {
        $set: { description: 'Updated test'}
    },{ 
        new: true 
    })
    .exec();
})
.then((dish) => {
    console.log(dish);

    dish.comments.push({
        rating: 5,
        comment: 'I'm getting a sinking feeling!',
        author: 'Leonardo di Carpaccio'
    });

    return dish.save();
})
.then((dish) => {
    console.log(dish);

    return Dishes.remove({});
})
.then(() => {
    return mongoose.connection.close();
})
.catch((err) => {
    console.log(err);
});

});

this is my dishes.js file:

    const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var commentSchema = new Schema({
    rating:  {
        type: Number,
        min: 1,
        max: 5,
        required: true
    },
    comment:  {
        type: String,
        required: true
    },
    author:  {
        type: String,
        required: true
    }
}, {
    timestamps: true
});


var dishSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    comments:[commentSchema]
}, {
    timestamps: true
});

var Dishes = mongoose.model('Dish', dishSchema);
module.exports = Dishes;

I am getting an error that says:

isNew: false,
  errors: undefined,
  _doc: {
    _id: 6207ff6455a72312f4426861,
    name: 'Uthappizza',
    description: 'Updated test',
    comments: CoreMongooseArray(0) [
      _path: 'comments',
      toBSON: [Function: toBSON],
      _atomics: {},
      _parent: [Circular *1],
      _cast: [Function: _cast],
      _markModified: [Function: _markModified],
      _registerAtomic: [Function: _registerAtomic],
      '$__getAtomics': [Function: $__getAtomics],
      hasAtomics: [Function: hasAtomics],
      _mapCast: [Function: _mapCast],
      push: [Function: push],
      nonAtomicPush: [Function: nonAtomicPush],
      '$pop': [Function: $pop],
      pop: [Function: pop],
      '$shift': [Function: $shift],
      shift: [Function: shift],
      pull: [Function: pull],
      splice: [Function: splice],
      unshift: [Function: unshift],
      sort: [Function: sort],
      addToSet: [Function: addToSet],
      set: [Function: set],
      toObject: [Function: toObject],
      inspect: [Function: inspect],
      indexOf: [Function: indexOf],
      remove: [Function: pull],
      id: [Function: id],
      create: [Function: create],
      notify: [Function: notify],
      isMongooseDocumentArray: true,
      validators: [],
      _schema: [DocumentArray],
      _handlers: [Object]
    ],
    createdAt: 2022-02-12T18:41:40.049Z,
    updatedAt: 2022-02-12T18:41:40.096Z,
    __v: 0
  }

the issue is in the output of the comments part, can someone pls help me?
I have tried reading about it online, but i am not able to get anything where is the problem?

Ps: this is a part of course, I have followed all the steps very carefully, but I am still getting the problem

Javascript Multiplying Within an Array

I have an array with multiple arrays inside. I would like to multiply the contents of each array.

Here is my code–currently not getting anything in console.
The desired output is 3 numbers– the result of multiplication of the three arrays

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    mult *= arr[i][j]
  }
  console.log(mult)
}

shuffle n elements in html list (see the code)

I’m trying to complete this code I have a list of 30 items. I want to show randomly: 2 elements between 1 and 10, 4 between 10 and 20 and 6 between 20 and 30. The code I show can only show the first two elements between 1 and 10…what can I do to show the other elements?

var list = document.getElementById("items"),
newlist = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0,10), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);
    
    list.innerHTML = "";
  
    while(i < 2)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
window.onload = shuffleNodes;
<dl id="items">
    <dd>1. item.<br></dd>
    <dd>2. item.<br></dd>
    <dd>3. item.<br></dd>
    <dd>4. item.<br></dd>
    <dd>5. item.<br></dd>
    <dd>6. item.<br></dd>
    <dd>7. item.<br></dd>
    <dd>8. item.<br></dd>
    <dd>9. item.<br></dd>
    <dd>10. item.<br></dd>
    <dd>11. item.<br></dd>
    <dd>12. item.<br></dd>
    <dd>13. item.<br></dd>
    <dd>14. item.<br></dd>
    <dd>15. item.<br></dd>
    <dd>16. item.<br></dd>
    <dd>17. item.<br></dd>
    <dd>18. item.<br></dd>
    <dd>19. item.<br></dd>
    <dd>20. item.<br></dd>
    <dd>21. item.<br></dd>
    <dd>22. item.<br></dd>
    <dd>23. item.<br></dd>
    <dd>24. item.<br></dd>
    <dd>25. item.<br></dd>
    <dd>26. item.<br></dd>
    <dd>27. item.<br></dd>
    <dd>28. item.<br></dd>
    <dd>29. item.<br></dd>
    <dd>30. item.<br></dd>
</dl>

using form data to send request similar to JSON

I’m making a web app (next.js) that’s pretty similar to fiverr. basically my update gig API endpoint requires that the request body be something like this:

{
  gig: { ...fields_related_to_gig },
  portfolioItems: [ {
    title: "",
    description: "",
    image: // a file
  } ] // basically the items that get displayed in your gig's portfolio
 }

Because im sending files with the request I need tp use form data. but then again I have arrays and nested objects which dont translate well into form data. I need some guidance as to how to pull this off. Should I straight up change the request format? should I JSON.stringify everything on front and decode on backend?

what are the best practices when it comes to sending files along with arrays of objects in the request body?

Vertical scroll slider with anchor link

I’m a JavaScript novice and I’m trying to make something on my own. In this case I’ve created a fake vertical slider that actually works with the normal page scroll. However, I’ve chosen to insert a menu on the right-hand side which allows you to navigate between the slider elements by means of anchor links.
Next to this menu there is a svg representing an upward and a downward arrow which can act as trigger points to scroll between the slider elements.

I have set up the highlighting of the active element and I was able to set the anchor link to the click of the arrows and the recognition of the next or previous one.

What I can’t manage to set is the synchronisation between the various scroll options. In fact, if I scroll with the mouse or click on one of the elements, the arrows do not update their position.

I hope I can explain this.

I share the reference JSFiddle. (Sorry for the spartan graphic appearance).

You can see it better implemented here

$(document).ready(function() {
  var $currentElement = $(".single-product").first();

  $("#down").click(function() {
    var $nextElement = $currentElement.next('.single-product');
    // Check if the next element exists by measuring its length
    if ($nextElement.length) {
      // Se esiste, aggiorna l'elemento corrente e scorre
      $currentElement = $nextElement;
      $('html, body').stop(true).animate({
        scrollTop: $nextElement.offset().top
      }, 1000);
    }
    return false;
  });

  $("#up").click(function() {
    var $prevElement = $currentElement.prev('.single-product');
    // Check if the next element exists by measuring its length
    if ($prevElement.length) {
      // Se esiste, aggiorna l'elemento corrente e scorre
      $currentElement = $prevElement;
      $('html, body').stop(true).animate({
        scrollTop: $prevElement.offset().top
      }, 1000);
    }
    return false;
  });

  //highlight anchor link on scroll

  // Cache selectors
  var topMenu = $("#product-menu"),
    topMenuHeight = topMenu.outerHeight() + 100,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function() {
      var item = $($(this).attr("href"));
      if (item.length) {
        return item;
      }
    });

  // Bind to scroll
  $(window).scroll(function() {
    // Get container scroll position
    var fromTop = $(this).scrollTop() + topMenuHeight;

    // Get id of current scroll item
    var cur = scrollItems.map(function() {
      if ($(this).offset().top < fromTop)
        return this;
    });

    // Get the id of the current element
    cur = cur[cur.length - 1];
    var id = cur && cur.length ? cur[0].id : "";
    // Set/remove active class
    menuItems
      .parent().removeClass("active")
      .end().filter("[href='#" + id + "']").parent().addClass("active");
  });
});
.scroll-slider-container{
  display:flex;
  align-items:flex-start;
}
.product-container{
  width:70%;
}
.navigation-container{
  width:30%;
  position:fixed;
  right:0;
}

.single-product{
  height:700px;
  background: url(https://development.nutfordesign.com/wp-content/uploads/2021/10/img-slide-1.png);
}

#product-menu{
  display:flex;
  align-items:center;
}
 #menu-product-side-menu{
    display:flex;
    flex-direction:column;
    justify-content:flex-end; 
  }
 .nav-arrows{
   width:30px;
 }
 .active{
    font-weight:700!important;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scroll-slider-container">
<div class="product-container">
<div id="product-1" class="single-product">
<h2>Prodotto 1</h2>
</div>
<div id="product-2" class="single-product">
<h2>Prodotto 2</h2>
</div>
<div id="product-3" class="single-product">
<h2>Prodotto 3</h2>
</div>
<div id="product-4" class="single-product">
<h2>Prodotto 4</h2>
</div>
</div>
<div id="product-menu" class="navigation-container">
<ul id="menu-product-side-menu "class="nav-list">
<li><a href="#product-1">Prodotto 1</a></li>
<li><a href="#product-2">Prodotto 2</a></li>
<li><a href="#product-3">Prodotto 3</a></li>
<li><a href="#product-4">Prodotto 4</a></li>
</ul>
<div class="nav-arrows">
<svg version="1.1" id="double-arrow" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
     y="0px" viewBox="0 0 200 2000" style="enable-background:new 0 0 200 2000;" xml:space="preserve">
<style type="text/css">
    .st0{opacity:2.000000e-02;fill:#FFFFFF;}
    .st1{fill:#1D1D1B;}
</style>
<a href="" id="down" class=" arrow next">
   <g>
    <rect y="1000" class="st0" width="200" height="1000"/>
    <path id="arrow-down" class="st1" d="M168.9,1867.9c-1.4-1.4-3.8-1.4-5.2,0c0,0,0,0,0,0l-60,60V1000h-7.4v927.9l-60-60
        c-1.4-1.4-3.8-1.4-5.2,0s-1.4,3.8,0,5.2l0,0l66.3,66.3c1.4,1.4,3.8,1.4,5.2,0c0,0,0,0,0,0l66.3-66.3
        C170.3,1871.7,170.3,1869.4,168.9,1867.9z"/>
</g>
  </a>
  
  <a href="" id="up" class="arrow prev">  
  <g>
    <rect class="st0" width="200" height="1000"/>
    <path id="arrow-up" class="st1" d="M168.9,132.1c-1.4,1.4-3.8,1.4-5.2,0c0,0,0,0,0,0l-60-60V1000h-7.4V72.1l-60,60
        c-1.4,1.4-3.8,1.4-5.2,0s-1.4-3.8,0-5.2l0,0l66.3-66.3c1.4-1.4,3.8-1.4,5.2,0c0,0,0,0,0,0l66.3,66.3
        C170.4,128.3,170.4,130.6,168.9,132.1C168.9,132.1,168.9,132.1,168.9,132.1z"/>
</g>
</a>
</svg>
</div>
</div>
</div>

How to use Jquery load along with functions?

So I am using Jquery load to load navigation bar on my website.
Here’s how im doing it

Homepage.html

<div id="nav-placeholder">

</div>
<script>
      jQuery(document).ready(function($) {
        jQuery("#nav-placeholder").load("navbar.html");
      });
</script>

navbar.html

<div class="navbar">
  <a href="#">Phemesoft</a>
  <a href="/studdash">Dashboard</a>
  <a href="/courselists">Courses</a>
  <a href="#">Live classes</a>
  <a href="#">Labs</a>
  <div class="search">
    
    <input id="searchqueryy"  name="searchquery" type="search" placeholder="Search" class="inputSearch" />
     <button onclick="searchfunction()" type="submit" class="searchButton">
           <i class="fa fa-search"></i>
        </button>
        
  </div>
  <!-- <button type="submit" class="searchbtn">
    <span class="material-icons">search</span>
  </button> -->
  <span class="material-icons">shopping_cart</span>
  <span class="material-icons">account_circle</span>
</div>

Since I have a server running, to load the navbar I have used app.get like so:

app.get("/navbar.html",function(request,response){
  response.sendFile(path.join(__dirname, "../client/App/", "navbar.html"));
});

And the search function looks like this:

<script>
  function searchfunction(){
    var searchquery = document.getElementById('searchqueryys').value;
    window.location.href = "/search/"+searchquery;
  }
  </script>

Now the problem is, after loading the navigation bar using jQuery.load, searchfunction isn’t working. I tried putting the searchfunction() script inside navbar.html but it doesn’t work like that (maybe because navbar.html has already been loaded when homepage.html was opened?). So how do I make my search function work across pages while using jQuery.load?

setInterval() still triggering after clearInterval() in NodeJS

I have the following code setting and clearing an interval inside a NodeJS script.

Starting interval works fine, but when trying to clear it, the stopping interval console will trigger, but the interval will continue firing every minute.

app.get("/api", async (req, res) => {

    active = req.query.active;
    
    let interval = null;

    if (active == "true") {

        console.log("starting interval");

        interval = setInterval(async function() {
            try {
                const Posts = await getPosts();
                const Comments = await getComments();
                sendPosts().then(() => sendComments());

            } catch (e) {
                throw e;
            };
        }, 60000);

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: true});

    } else {

        console.log("stopping interval");

        clearInterval(interval);
        interval = null;

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: false});
    }
    
});

What am I missing?

Rotating Line around Point in p5.js

Goal: I’m trying to create a triangle given two angles (a0,b0). To do so, I’m trying to rotate a vector r0 by some angle a0 around one of the vertices of r0. Here’s a diagram illustrating my idea.
enter image description here
Problem: However, when I rotate the line, it seems to rotate around the origin. I’ve read many, many articles on how to fix this, but none of the suggested solutions (i.e., translate then rotate, push(), pop()) don’t seem to work, perhaps because I’m dealing with a line segment here. Below is my code.

MWE Code:

let angle = 0;

function setup(){
  createCanvas(600, 400);
  angleMode(DEGREES);
}

function draw(){
  let v1 = createVector(width/2 - 50, height/2);
  let v2 = createVector(width/2 + 50, height/2);

  background(255);
  stroke(0);
  strokeWeight(4);
  rotate(-1 * mouseX);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>

    <title>Billiards #2</title>
  </head>
  <body>
    <script src="sketch.js"></script>
  </body>
</html>

Any help is appreciated.

Mongoose add parentdoc if it doesn’t exist OR add subdoc if parent doc exists but subdoc doesn’t

Essentially, I have a User that has an email and a list of subscriptions. I want to create the User with the subscription if the user doesn’t exist, if the user exists but doesn’t have the subscription I Want to simply add the newSubscription to the Users list of subscriptions. Finally, if both User and subscription already exist then I want to handle the existing subscription in my own way.

await UserDocument.findOneAndUpdate(
            {'$and': [{
                'email': email,
            }, {
                'subscriptions.product': product-id,
            }]},
            {'$setOnInsert': newCustomerWithSubscription,
            '$push': {'email.$.subscription': newSubscription}},  
            {upsert: true, new: false},
            async function(err: CallbackError, doc: UserSchemaType | null) {
                //Code to handle if both exists
            }).exec();

DB Design:

User: {
    email,
    subscriptions: [{
        //sub-info
    }]
}

How can I get the actual height of the content,when -webkit-line-clamp: 2;-webkit-box-orient: vertical; and overflow:hidden is applied

So I have used two div to explain my question both div .text and text2 contains same data but .text has below CSS property:

.text {
   overflow: hidden;
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   transition: all 0.3s ease-in-out;
}

which text 2 has not,both has same data so but I want to know .text actual height even if above CSS applied.

document.getElementById('text2').innerHTML = "Height of below div is: " + document.querySelector(".text2").offsetHeight;

document.getElementById('text').innerHTML = "Height of below div is: " + document.querySelector(".text").offsetHeight;
.text {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: all 0.3s ease-in-out;
}
<div class="box">
  <p id="text"></p>
  <div class="text">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
  <br><br>
  <p id="text2"></p>
  <div class="text2">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div>