Mongoose update a very nested sub document

I have the following schema for a grid (evaluation grid). Grid => Sections => Criteria => Levels and I want to update a single Level element.

const mongoose = require("mongoose");

const levelSchema = mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    value: {
      type: Number,
      required: true,
    },
  },
  { timestamps: true }
);

exports.Level = mongoose.model("Level", levelSchema);

const criterionSchema = mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    levels: [levelSchema],
  },
  { timestamps: true }
);

criterionSchema.virtual("weight").get(function () {
  return Math.max(this.levels.map((level) => level.weigth));
});

exports.Criterion = mongoose.model("Criterion", criterionSchema);

const sectionSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    criteria: [criterionSchema],
  },
  { timestamps: true }
);

sectionSchema.virtual("weight").get(function () {
  return this.criteria.reduce((acc, criteria) => acc + criteria.weight, 0);
});

exports.Section = mongoose.model("Section", sectionSchema);

const schema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },

    sections: [sectionSchema],
    code: { type: Number, required: true },
    course: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Course",
      required: true,
    },
  },
  { timestamps: true }
);
schema.virtual("weight").get(function () {
  return this.sections.reduce((acc, section) => acc + section.weight, 0);
});

exports.Grid = mongoose.model("Grid", schema);

I was able to retrieve a specific Level’s Grid with this code :

Grid.findOne({"sections.criteria.levels._id": levelId})

So I tried FindOneAndUpdate with this code :

const grid = await Grid.findOneAndUpdate(
      { "sections.criteria.levels._id": req.params.levelId },
      {
        $set: {
          "sections.$[].criteria.$[].levels.$[].title": req.body.title,
        },
      },
      { new: true });

But, it changed ALL the Levels of the grid.

How can we update a single Level sub, sub, sub document and returns it ?

HTTP Error 405 when JS is in its own file, but not when in HTML

I have a small text censor web app im working on. Whenever the .js is in its own file and I click the ‘censor text’ button, I get a HTTP error 405, but if i put the js in the HTML tag, it works fine.Not too sure why.

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Censor</title>
    <script src="/js/main.js"></script>
</head>

<body>
    <h1>Text Censor</h1>
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Rerum enim reiciendis recusandae aliquid delectus
        consectetur nobis. Sunt exercitationem iure dolores provident obcaecati aliquam totam. Molestiae cumque ducimus
        aliquid. Deserunt, provident.</p>
    <form name="redacted" method="post" action="">
        <textarea id="input" name="text" rows="10" cols="60">
        </textarea>
        <br />
        <input id="formSub" type="submit" value="Censor Text" />
    </form>
</body>
</html>

JS:

var div = document.getElementById('formSub');

function censorWords(event) {
   event.preventDefault();
   var textContent = document.getElementById('input');
   var redacted = ["boston", "red", "sox"];
   console.log(textContent.value)
   textContent.value = censored(textContent.value, redacted);
}

function censored(string, filters) {
   console.log('in')
   // "i" ignores case, "g" for global and "|" for OR match
   var regexp = new RegExp(filters.join("|"), "gi");
   return string.replace(regexp, function (match) {
       //this is where the words are replaced with X
       var censorship = '';
       for (var i = 0; i < match.length; i++) {
           censorship += 'x';
       }
       return censorship
   })
}

div.addEventListener('click', censorWords)

How to highlight items in a select multiple using angularJS?

For some reason that is too long to explain I am trying to modify the behaviour of a select multiple, what I want to achieve is to allow the user to select multiple elements without the need to hold the ctrl/cmd key. this is the html:

<select multiple="multiple" class="form-control">
    <option ng-repeat="option in options" ng-click="selectItem(option)" ng-selected="option.selected" value="{{option.id}}">{{option.name}}</option>
</select>

and this is my selectItem function:

$scope.selectItem = (option) => {
    let index = $scope.selectedElements.indexOf(option.id);
    (index === -1) ? $scope.selectedElements.push(option.id) : $scope.selectedElements.splice(index, 1);
    
    $scope.options.forEach((element, index) => {
        element.selected = $scope.selectedElements.indexOf(element.id) !== -1 ? true : false;
    });
}

this is partially working: the $scope.selectedElements array is updated and also the $scope.options has the selected property correctly set to true or false. However the select only shows as highlighted the last element I clicked on.

Am I missing something?

Slider won’t work when numbers are like 0.1 – 0.9

I have a Slider which outputs the Values as labels.
When I set the input like this:

<input type="range" min="0" max="850" value="620" step="10" class="two-range-slider__input js-two-range-slider-input">
<input type="range" min="0" max="850" value="220" step="10" class="two-range-slider__input js-two-range-slider-input">

With high values, I don’t have any problems, but when I have small numbers like you see below, the values won’t change in the labels and I don’t have my range shown inbetween the thumbs.

For my intentions I need to be able to have a Slider within the range of 0.1 -> 0.9

$(document).ready(function() {

      const twoRangeSlider = (() => {
        const rangeCheck = (rangeInputs, rangeMinOutput, rangeMaxOutput) => {
          const rangeMin = rangeInputs[0].min ? rangeInputs[0].min : 0;
          const rangeMax = rangeInputs[0].max ? rangeInputs[0].max : 100;
          let rangeMinValue = parseInt(rangeInputs[1].value);
          let rangeMaxValue = parseInt(rangeInputs[0].value);

          rangeMinValue = Math.min(Math.max(rangeMinValue, rangeMin), rangeMaxValue);


          const rangeMinPercentage = Number(
            ((rangeMinValue - rangeMin) * 100) / (rangeMax - rangeMin));
          const rangeMaxPercentage = Number(
            ((rangeMaxValue - rangeMin) * 100) / (rangeMax - rangeMin));


          rangeInputs[0].style.background = `linear-gradient(to right, #007cc1 ${rangeMaxPercentage}%, #c4c8ca ${rangeMaxPercentage}%)`;
          rangeInputs[1].style.background = `linear-gradient(to right,#c4c8ca ${rangeMinPercentage}%, transparent ${rangeMinPercentage}%)`;


          rangeMinOutput.innerHTML = `<strong style="margin-left: 13px; font-size: 11px;">Min</strong> <br>${rangeMinValue}mm`;
          rangeMaxOutput.innerHTML = `<strong style="margin-left: 13px; font-size: 11px;">Max</strong> <br>${rangeMaxValue}mm`;
        };

        const bindComponent = (item) => {
          const rangeInputs = item.querySelectorAll('.js-two-range-slider-input');
          const rangeMinOutput = item.querySelector('.js-two-range-slider-min-value');
          const rangeMaxOutput = item.querySelector('.js-two-range-slider-max-value');

          item.addEventListener("input", () => {
            rangeCheck(rangeInputs, rangeMinOutput, rangeMaxOutput);
          });

          rangeCheck(rangeInputs, rangeMinOutput, rangeMaxOutput);
        };

        const init = () => {
          const rootEl = document.getElementsByClassName("js-two-range-slider");
          [...rootEl].forEach((item) => bindComponent(item));
        };

        return {
          init
        };
      })();

      twoRangeSlider.init();
.two-range-slider {
  position: relative;
  height: 4px;
  width: 164px;
  margin-bottom: 50px;
}

.two-range-slider__input {
  position: absolute;
  left: 47%;
  top: 28px;
  box-shadow: 0;
  appearance: none;
  width: 100%;
  height: 3px;
  border-radius: 50px;
  background-color: #CED4DA;
  outline: 0;
}

.two-range-slider__input::-webkit-slider-thumb {
  z-index: 2;
  position: relative;
  -webkit-appearance: none;
  appearance: none;
  width: 17px;
  height: 17px;
  border-radius: 50%;
  background: #000;
  cursor: pointer;
}

.two-range-slider__input::-moz-range-thumb {
  z-index: 2;
  position: relative;
  appearance: none;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  border: 0;
  background: #FFFFFF;
  cursor: pointer;
}

.two-range-slider__output {
  display: inline-flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  width: 200%;
  margin-top: 0px;
  margin-left: 0px;
  color: #808080;
}
<div class="two-range-slider js-two-range-slider">
                                                <input type="range" min="0" max="1" value="0.8" step="0.1" class="two-range-slider__input js-two-range-slider-input">
                                                <input type="range" min="0" max="1" value="0.4" step="0.1" class="two-range-slider__input js-two-range-slider-input">

                                                <div class="two-range-slider__output">
                                                    <output class="two-range-slider__value js-two-range-slider-min-value"></output>
                                                    <output class="two-range-slider__value js-two-range-slider-max-value"></output>
                                                </div>

                                            </div>

How to modify element upon it exiting “sticky” state?

I’ve got an element stickied to the bottom of the viewport. I am trying to have it change text upon reaching its “destination”, i.e. when it stops sticking.

I found a somewhat relevant solution elsewhere online, but I can’t quite get it to work… It almost does the trick, but it only goes into effect once the element comes in contact with the top of the viewport. Whereas I want it to turn pink once it stops sticking, immediately when it touches the blue element.

I’ve looked around for about a week now and I still can’t find a way to make this happen, nor have I had any success through pure trial and error…

Hopefully some of you wizards here know how I can achieve this.

Link to codepen: https://codepen.io/darkwing/pen/WNwVXKx

Please ignore that the element starts out pink below if you don’t use the link above.

const el = document.querySelector(".myElement")
const observer = new IntersectionObserver( 
  ([e]) => e.target.classList.toggle("is-pinned", e.intersectionRatio < 1),
  { threshold: [1] }
);

observer.observe(el);
#parent { 
  height: 2000px; 
}

.filler {
  background-color: green;
  height: 500px;
}

.myElement {
  width: 300px;
  height: 200px;
  background-color: red;
    position: sticky;
    bottom: 0;
}

.otherElement {
  width: 300px;
  height: 200px;
  background-color: blue;
}

/* styles for when the header is in sticky mode */
.myElement.is-pinned {
  background-color: pink;
} 
<div id="parent">
  
  <div class="filler"></div>
  <div class="myElement"></div>
  
  <div class="otherElement"></div>
  
</div> 

React Native how to get only some data from api

Given url Data==> need to get only Karnataka state details
[{“id”:1,”title”:”TELANGANA”,”image”:”url”,”stateCode”:”TS”},{“id”:4,”title”:”TAMILNADU”,”image”:”url”,”stateCode”:”TN”},{“id”:3,”title”:”KARNATAKA”,”image”:”url”,”stateCode”:”KN”},{“id”:2,”title”:”ANDHRA”,”image”:”url”,”stateCode”:”AP”}]

Here code to get data===>

const [states, setStates] = useState([]);

useEffect(() => {
    handleGetStates()
}, []);


const handleGetStates = async () => {
    let values = {
        url: `url`,
        method: 'get',
        
    }
    try {
        const response = await axios(values)
        setStates(response.data)
        console.log(response.data,'response');
    } catch (error) {
        // handle error
        console.log(error);
    }
};

Just reload the data for one specific entity of a list using useQuery

Let’s say I load a list of entities using the useQuery hook of React Query. After updating one entity of this list I don’t want the whole list to be reloaded, just the data for this specific entity.

How could you implement this behaviour using the useQuery hook? Is it possible to specify that React Query should not reload the whole list and just reload the data for this specific entity?

Thank you for your help.

Google Analytics Data API – HTML to Apps Script: gapi is not defined

I am trying to execute a Report with the Google Analytics Data API. I built the request using Google’s documentation and I get this script. The script works well if I execute it directly with the “Try this method” option in the documentation:

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for analyticsdata.properties.runReport
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("YOUR_API_KEY");
    return gapi.client.load("https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.analyticsdata.properties.runReport({
      "property": "properties/295880876",
      "resource": {
        "metrics": [
          {
            "name": "sessions"
          },
          {
            "name": "conversions"
          },
          {
            "name": "totalRevenue"
          }
        ],
        "dimensions": [
          {
            "name": "week"
          },
          {
            "name": "year"
          }
        ],
        "dateRanges": [
          {
            "startDate": "2021-01-01",
            "endDate": "today"
          }
        ]
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

Now I want to run this Script in Apps Script and import the Data to a spreadsheet. However as this is a HTML, if I want to run it as a JS and delete the script tags and content I receive “gapi is not defined”.

It is clear that I still have to load https://apis.google.com/js/api.js somehow, but how?

Thanks for your help!

Countdown Timer every 15-Minutes in the hour

I have a webinar that runs every 15 minutes of every hour of the day (EG: 11:00, 11:15, 11:30 & 11:45).

I’d like a countdown timer that shows the remaining minutes until the next start time and all I can find from days of searches and trying to figure this out myself is an hourly countdown.

My question is, how do I update this code for be every 15 minutes not every 60.

<script>
/* Return minutes and seconds to next hour
** @returns {Object} minutes: minutes remaining
**                   seconds: seconds remaining
*/
function getTimeRemaining() {
  var t = Date.now();
  var seconds = (60 - Math.floor(t % 6e4 / 1e3)) % 60;
  var minutes = 60 - Math.ceil(t % 3.6e6 / 6e4) + (seconds? 0:1);
  return {
    'minutes': ('0' + minutes).slice(-2),
    'seconds': ('0' + seconds).slice(-2)      };
}

// Simple show remaining function
function showRemaining() {
  var r = getTimeRemaining();
  document.getElementById('clock').textContent = (r.minutes + ':' + ('0' + r.seconds).slice(-2));
  // Run again just after next full second
  setTimeout(showRemaining, 1020 - (Date.now() % 1000));
}

showRemaining();
</script>

Uncaught (in promise) TypeError: date.toDate is not a function on a timestamp got from firebase

after some time i’ve been programming and using my web app an error has occurred:

Uncaught (in promise) TypeError: date.toDate is not a function
    at eval (script.js:41:28)
    at eval (index.esm2017.js:18519:15)
    at eval (index.esm2017.js:13962:53)
    at Gt.inorderTraversal (index.esm2017.js:2365:49)
    at Gt.inorderTraversal (index.esm2017.js:2365:87)
    at Gt.inorderTraversal (index.esm2017.js:2365:87)
    at qt.inorderTraversal (index.esm2017.js:2269:26)
    at Lu.forEach (index.esm2017.js:13962:24)
    at Mh.forEach (index.esm2017.js:18518:29)
    at eval (script.js:37:14)

by the way this error showed the first time just few minutes ago randomly without any update at the code, despite this error everything keep working great but in my opinion this error in the console is annoying.
I can’t figure out why this is happening … every doc from firebase is read correctly…

getDocs(orderRef).then((snapshot) => {
    // console.log(snapshot.docs);
    snapshot.forEach((doc) => {
        idArray.push(doc.id);
        const { title, summary, date, subscriptionDate } = doc.data();

        let dateStr = date.toDate().toLocaleDateString();
        let submitDateStr = subscriptionDate.toDate().toLocaleDateString("it-IT", {hour: "numeric", minute: "numeric"});

        getTodoList(title, summary, dateStr, submitDateStr, index);
        index += 1;
    })
});

any tip?

How do I pass multiple paramaters in javaScript Window command

I have a single page application that has back navigation via a back link shown at the top of the page.
Each screen of the application has it’s own function, I store the function name and parameters in arrays and have an event listener which uses the JS window function to call the function.

    prevPage="showPage1";
    prevParm=['a','b'];     

    prevParm1=("a","b");
    prevParm2='a,b';
    prevParm3=("a","b","c");    

    //window["navHelper"][prevPage](prevParm);
    //window["navHelper"][prevPage]("a","b"); // works 
    //window["navHelper"][prevPage]["a","b"]; 
    
    
    window["navHelper"][prevPage](prevParm3);

showPage1 is a function within the navHelper class

This works for a single parameter but not where there are multiple parameters.

How do I pass two parameters to function using window? I tried passing an array and various other methods and can’t get it to work.

There is a jsfiddle showing the issue here:
https://jsfiddle.net/zacmarshall/j6Lxa0u1/3/

Fabric js object guides for itext not positioning correctly

I am using the default fabric js aligning guidelines. Other objects like rectangles are aligning correctly but when I try to align two Itext objects the alignment is off as in this image. The aligning guidelines show that the two Itext objects are correctly aligned at the bottom but when you take a look at them the one on the right seems a little bit lower. The Itext objects object on the left is scaled hence bigger than the one on the right. Selecting both of the Itext shows that the bounding boxes of the two Itext objects are actually aligned. Seems like when I scale up an Itext object it introduces padding that makes the text objects not align correctly.

Any ideas or workarounds to this problem? I also tried to use the editor of printio.ru that one of the founders of fabric js made and realized it has the same problem.