Mongoose schema field wont update its values

In a Next.js project, I have the below Wallet schema :

const walletSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
      maxlength: 20,
    },
    user: { type: String, required: true },
    transactions_count: { type: Number, required: true, default: 0 },
    expenses_transactions_count: {
      type: Number,
      required: true,
      default: 0,
    },
    income_transactions_count: {
      type: Number,
      required: true,
      default: 0,
    },
    balance: { type: Number, required: true, default: 0 },
    expenses: { type: Number, required: true, default: 0 },
    income: { type: Number, required: true, default: 0 },
  },
  { timestamps: true, minimize: false }
)

walletSchema.index({ user: 1, title: 1 }, { unique: true })

walletSchema.plugin(uniqueValidator, {
  message: "{PATH} {VALUE} already exists.",
}) 

New doc is created by passing only the 2 non-defaulted values :

 const wallet = new WalletModel({ title, user })
 await wallet.save()

And the below Transaction schema :

const transactionSchema = new Schema(
  {
    wallet_id: { type: String, required: true },
    category_id: { type: String, required: true },
    user: { type: String, required: true },
    amount: { type: Number, required: true },
    type: { type: String, required: true },
    date: {
      type: String,
      default: moment().format("YYYY-MM-DD"),
      required: true,
    },
    description: { type: String, required: true },
  },
  { timestamps: true }
)

Which is created like so :

    const transaction = new TransactionModel(payload)
    await transaction.save()

I also have a pre(“save”) middleware on the Transaction where im trying to modify the Wallet field based on the incoming new Transaction document, like updating the income,expenses values, incrementing totals etc..

transactionSchema.pre("save", async function (next) {
  try {

     const wallet = await model("wallet").findOne({ _id: this.wallet_id })
      
      if(this.type === "expense"){
      wallet.balance: -= transaction.amount
      wallet.expenses: += transaction.amount
      //wallet.income: //not used here
      //wallet.income_transactions_count: //not used here
      wallet.expenses_transactions_count: expenses_transactions_count += 1
      wallet.transactions_count: number

     await wallet.save()
}

///the same for income type etc
...
    
    next()
  } catch (error: any) {
    next(error)
  }
})

For some very curious reason, the fields income_transactions_count,expenses_transactions_count and transactions_count sometimes change and sometimes dont.
The reason is that sometimes they have undefined values at the time i’m trying to modify them and the mind blowing thing is that when i log the value of wallet right after const wallet = await model... i get all the values without issues, but when i do the same thing inside the if statement, ONLY those 3 return undefined and not every time ! Sometimes they have their correct values as expected !

Google Sheets spreadsheets.values.update not working when using axios

I am working on a simple internal react native application for my company. I am trying to update an excel sheet using google’s apis via axios requests. I have used Google’s oAuth (via Firebase) and am authenticated properly.

Here is the code (be advised that some of the variables are not used yet. I will update that when this code works):

const doWriteToGoogleSheets = async (sheetId, sheetName, range, majorDimension) => {
    await axios.put(`https://sheets.google.com/v4/spreadsheets/${sheetId}/values/${sheetName}!${range}?valueInputOption=${VALUE_INPUT_OPTION.USER_ENTERED}&key=${AUTH_SHEETS_API_KEY}`, {
        range: `${sheetName}!${range}`,
        majorDimension: "ROWS",
        values: [
            ["NAMESS"] // test value, try with only 1 cell as the range
        ],
    })

}

I have also tested using:

    await axios.put(`https://sheets.google.com/v4/spreadsheets/${sheetId}/values/'TimeFullYear (Input Here)'!A1?valueInputOption=${VALUE_INPUT_OPTION.USER_ENTERED}&key=${AUTH_SHEETS_API_KEY}`, {
        "range": "'TimeFullYear (Input Here)'!A1",
        "majorDimension": "ROWS",
        "values": [
            [
                "NAMESS"
            ]
        ]
    })

and

  await axios.put(`https://sheets.google.com/v4/spreadsheets/${sheetId}/values/'TimeFullYear (Input Here)'!A1?valueInputOption=${VALUE_INPUT_OPTION.USER_ENTERED}&key=${AUTH_SHEETS_API_KEY}`, {
        range: "TimeFullYear (Input Here)!A1",
        majorDimension: "ROWS",
        values: [
            [
                "NAMESS"
            ]
        ]
    })

THE PROBLEM

My logger is saying that the code completed successfully (no error was thrown) but then I get “undefined” as a response (after the “:” is where the response should be):

SUCCESS - write to timecards: undefined

And when I check in the google sheet nothing is updated.

WHAT I KNOW

HELP

can someone help me out?

EDIT

Problem with using protobuf in vue 3 composition api

I’m trying to use a protobuf file to communicate with a server. I tried to use protobufjs library but I can’t import in vue 3. The documentation says import the library like this:

var protobuf = require("protobufjs");

but there is no "require" in vue 3. What is the workaround to make this work or even is there any other library to use protobuf in vue 3 easily?
I’m beginner in js and any help would be appreciated.
Thanks.

How to override _id in mongoose

I have a schema like this:

const sessionCardSchema = new Schema(
    {
        unit: Number,
        creator: String
    }
);

I can save a card like this:

const Card = {
  unit: 2,
  creator: 'Jack'
}
const sessionCard = new db.SessionCard(Card);
await sessionCardModel.save(); 

The issue is I cannot save my own objectId as _id of the document.

Here is what I tried:

My schema:

const sessionCardSchema = new Schema(
    {
        
        // _id: mongoose.Schema.Types.ObjectId,
        unit: Number,
        creator: String

    }, { _id: false }
);

My code:

const Card = {
  _id: '657c95a4b6e31b1c968aec94'
  unit: 2,
  creator: 'Jack'
}
const sessionCard = new db.SessionCard(Card);
await sessionCardModel.save(); 

Embed libsodium.js in Google Chrome Extension Manifest V3

I am trying to use libsodium.js, a C-library that has been transpiled to WASM with Emscripten.

I have found two (1, 2) related posts that are now out of date and/or incomplete:

  1. This old issue identifies that the Chrome Extension environment prevents the use of eval(), which for some reason libsodium.js does upon initialization. In Manifest V3, there doesn’t appear to be a way to allow this this other than sandboxed pages, which I will address below. Also, the example project they linked is not for Manifest V3.
  2. The answer to this post is a dead link that is not archived, but seems to imply using a iframe and passing messages between it and the containing DOM. This is likely a moot point as I want to use libsodium.js from my background service worker anyway.

What I have tried:

  • I have successfully gotten sodium.js (the standalone build variant) to load and work when linked in the sandbox page, however, it seems, by design, the sandbox page has no means to communicate back to my extensions background service worker, not even external page messaging or window.postMessage(). The chrome.* API is not available in this environment.
  • Importing using methods in this post.
    • importScripts() in the background service worker, which gets me right back to violating extension CSP. (Uncaught (in promise) RuntimeError: Aborted(CompileError: WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because neither 'wasm-eval' nor 'unsafe-eval' is an allowed source of script in the following Content Security Policy directive: "script-src 'self'"). Build with -sASSERTIONS for more info.)
    • Loading the module build variant in my background service worker like import {_sodium} from '../thirdparty/js/libsodium-wrappers.js;'; after configuring my manifest.json to "background": { "service_worker": "js/background.js", "type": "module"}. This results in the error Uncaught SyntaxError: The requested module '../thirdparty/js/libsodium-wrappers.js' does not provide an export named '_sodium'.
    • Loading the module build variant in my background service worker like import '../thirdparty/js/libsodium-wrappers.js';. This results in the error Uncaught TypeError: Cannot read properties of undefined (reading 'sodium').

AssertionError: promise resolved “undefined” instead of rejecting

I have these functions

export async function doStuff1(): Promise<void> {
  const a = 2;
  match(a).with(2, async () => {
    await doStuff2();
  });

  console.log("not implemented");
}

export async function doStuff2(): Promise<void> {
  throw new Error("not implemented");
}

and this in the tests

await expect(
   doStuff1()
).rejects.toThrowError(Error);

The test fails and it says Vitest caught 1 unhandled error during the test run. and AssertionError: promise resolved "undefined" instead of rejecting.

What am I doing wrong? If I replace my match with a simple if/else the test works fine.

JavaScript WebGrid type game

I’m a beginner with only 2 months experience in front-end. I’m trying to make a simple web-grid game.

I’ve got a 10×10 grid table (grid container with 100 div child elements in it), and my goal is that, when the site is opened, a random grid item out of the 100 gets automatically selected, and when the user clicks on that randomly selected grid item, another grid item out of the 100 gets randomly selected automatically, and the previously selected item gets de-selected (color goes back to the default state for example).

I was thinking I could do something with Math.random, but I don’t know how. Any help or suggestions is appreciated!

HTML code is just

<div class="grid-container"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <!-- ... a hundred of these child elements for 10x10. -->
</div>

JavaScript is blank

Rails stimulus controller firing on one page, but not another

The following javascript/controllers/index.js file

import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
import {
  PasswordConfirmController,
  PasswordPeekController,
} from "stimulus-library";
application.register("password-confirm", PasswordConfirmController);
application.register("password-peek", PasswordPeekController);

is firing on action /users/sign_in which calls a partial devise/sessions/_new.html.erb.
However if that partial is included in a home/index.html.erb action, the password-peek action is reacting the click action of the link

<%= content_tag("a", data: { action: 'password-peek#toggle'} ) do %>
  <%= fa_icon('eye', class: 'fa-lg') %> / <%= fa_icon('eye-slash', class: 'fa-lg') %>
<% end %>

but not firing the expected action of toggling the password. Both headers reference the same index.js file

<script type="importmap" data-turbo-track="reload">{
  "imports": {
[...]
/assets/controllers/index-
66295387b69c17c084270ed3a3c3682daecc9866d3b7af4a3e9dc3b01e362883.js

Why is that?

HTML5 Banner Ad Loops 3 times but resets after Exit click opens a new window. How can I stop this?

The banner ad should only loop 3 times. Clicking the banner opens an Exit URL in another tab. When you go back to the banner ad tab the ad has reset and starts playing again. I’d like it to stop after 3 plays no matter what.

I assume this is a javascript coding issue. I’m not a coder but can understand basic html. Any help would be great!

(function() {
  function onImagesLoaded(container, event) {
    var preloads = [];
    preloads.push.apply(preloads, container.getElementsByTagName("img"));
    preloads.push.apply(preloads, container.getElementsByTagName("lottie-player"));
    preloads.push.apply(preloads, container.getElementsByTagName("video"));
    var loaded = preloads.length;
    for (var i = 0; i < preloads.length; i++) {
      var tag = preloads[i].tagName.toLowerCase();
      if (tag === "lottie-player") {
        preloads[i].addEventListener("ready", function() {
          loaded--;
          if (loaded == 0) {
            event();
          }
        });
      } else if (tag === "video") {
        preloads[i].addEventListener('loadeddata', function() {
          loaded--;
          if (loaded == 0) {
            event();
          }
        }, false);
      } else if (tag === "img") {
        if (preloads[i].complete) {
          loaded--;
        } else {
          preloads[i].addEventListener("load", function() {
            loaded--;
            if (loaded == 0) {
              event();
            }
          });
        }
        if (loaded == 0) {
          event();
        }
      }
    }
  }

  onImagesLoaded(document.getElementById("b_13"), function() {
    var elements = document.getElementById("b_13").getElementsByClassName('js-bnfy');
    for (var i = 0; i < elements.length; i++) {
      elements[i].style.display = 'block';
    }

    var playCount = 0;
    var lastPlay = false;
    var animationInterval;
    var exitTimeouts = [];

    function clearExitTimeouts() {
      exitTimeouts.forEach(clearTimeout);
      exitTimeouts = [];
    }

    function handleVisibilityChange() {
      if (document.hidden) {
        clearInterval(animationInterval);
        clearExitTimeouts();
      } else {
        replayAnimations();
        animationInterval = setInterval(replayAnimations, 9000);
      }
    }

    document.addEventListener("visibilitychange", handleVisibilityChange);

    function handleExits() {
      var el_img_9535 = document.getElementById("img_9535");
      var el_img_11122 = document.getElementById("img_11122");
      var el_img_9529 = document.getElementById("img_9529");
      var el_img_11124 = document.getElementById("img_11124");
      var el_img_4533 = document.getElementById("img_4533");

      el_img_4533.className = "bnfy-enter";
      var timeout = setTimeout(function() {

        el_img_4533.className = '';
        void el_img_4533.offsetWidth;
        el_img_4533.className = "bnfy-exit";
      }, 3200);
      exitTimeouts.push(timeout);
      var el_img_9534 = document.getElementById("img_9534");

      el_img_9534.className = "bnfy-enter";
      var timeout = setTimeout(function() {

        el_img_9534.className = '';
        void el_img_9534.offsetWidth;
        el_img_9534.className = "bnfy-exit";
      }, 3200);
      exitTimeouts.push(timeout);
      var el_img_9533 = document.getElementById("img_9533");

      el_img_9533.className = "bnfy-enter";
      var timeout = setTimeout(function() {

        el_img_9533.className = '';
        void el_img_9533.offsetWidth;
        el_img_9533.className = "bnfy-exit";
      }, 3600);
      exitTimeouts.push(timeout);
      var el_img_4528 = document.getElementById("img_4528");
      var el_img_4526 = document.getElementById("img_4526");
      var el_img_13 = document.getElementById("img_13");
    }

    handleExits();
    var playbackLoop = animationInterval = setInterval(function() {
      playCount = playCount + 1;
      lastPlay = playCount === 2;
      replayAnimations();

      if (playCount === 2) {
        clearInterval(playbackLoop);
      }
    }, 9000);

    function replayAnimations() {
      var banner = document.getElementById("b_13");
      if (banner) {
        var elements = banner.children;
        for (var i = 0; i < elements.length; i++) {
          if (elements[i] && elements[i].tagName.toLowerCase() !== 'script' && elements[i].tagName.toLowerCase() !== 'style' && elements[i].tagName.toLowerCase() !== 'noscript') {
            var display = elements[i].style.display;
            elements[i].style.display = 'none';
            void elements[i].offsetWidth;
            elements[i].style.display = display;
          }
        }
      }

      handleExits();
    }
  });
  if (!Enabler.isInitialized()) {
    Enabler.addEventListener(
      studio.events.StudioEvent.INIT,
      enablerInitialized);
  } else {
    enablerInitialized();
  }

  function enablerInitialized() {
    if (!Enabler.isVisible()) {
      Enabler.addEventListener(
        studio.events.StudioEvent.VISIBLE,
        adVisible);
    } else {
      adVisible();
    }
  }

  function adVisible() {
    function bgExitHandler(e) {
      Enabler.exit('Background Exit');
    }
    document.getElementById('b_13').addEventListener('click', bgExitHandler, false);
  }
})();

I tried editing the playcount but that didn’t work. i think it may need to use localstorage to save the playcount but I’m not sure how?

Barba.js page transition: ScrollTrigger not working after navigating to a new page

I am using Barba.js for page transitions in my project, and I have some issues with ScrollTrigger after navigating between pages.

For example, when I load the homepage, the once function runs perfectly, and everything works as expected. However, when I navigate to the “About” page from the navbar, the page loads, but ScrollTrigger does not work. If I refresh the “About” page manually, everything works fine again.

barba.init({
  timeout: 5000,
  transitions: [{
    name: 'default',

    async once() {
      runAll();
      preLoader();
    },

    async enter() {
      console.log("Enter: Refreshing ScrollTrigger");
      ScrollTrigger.refresh(true);
      await runAll();
    },

    async beforeEnter() {
      console.log("Before Enter");
      console.log(ScrollTrigger.getAll()); // Check the status
      ScrollTrigger.getAll().forEach(t => t.kill());
      console.log(ScrollTrigger.getAll()); // Check the status

      console.log("Before Enter: Refreshing ScrollTrigger");
      ScrollTrigger.refresh(true);
      console.log(ScrollTrigger.getAll()); // Check the status
      await runAll(); // Reinitialize necessary functions for the new page
    },
  }]
});

I added a console.log statement in the beforeEnter function, and the final getAll() returns an empty array.

Promise.withResolvers is not a function when using pdf.js 4.4.168

I am using pdf.js 4.4.168 to render some pdf in browser, today when I use safari 16.4 to open the site, shows error:

Unexpected Application Error!
Promise.withResolvers is not a function. (In 'Promise.withResolvers()', 'Promise.withResolvers' is undefined)
x_@https://tex.poemhub.top/assets/index--WBBKURE.js:35:156906
sV@https://tex.poemhub.top/assets/index--WBBKURE.js:35:152952
@https://tex.poemhub.top/assets/index--WBBKURE.js:45:77451
yl@https://tex.poemhub.top/assets/react-BFk0LVKl.js:32:24264
ur@https://tex.poemhub.top/assets/react-BFk0LVKl.js:32:42277
@https://tex.poemhub.top/assets/react-BFk0LVKl.js:32:40631
P@https://tex.poemhub.top/assets/react-BFk0LVKl.js:17:1585
oe@https://tex.poemhub.top/assets/react-BFk0LVKl.js:17:1954

I am searching from internet that tell me the legacy browser did not support Promise.withResolvers(), we should upgrade the browser to solve this problem. But I still want some old version of user should use the website. Then I tried to use the pdf.js legacy version. What I have tried to download the legacy version, then replace with the legacy one: https://github.com/mozilla/pdf.js/releases/download/v4.4.168/pdfjs-4.4.168-legacy-dist.zip.

After replace the pdf.worker.min.mjs, still did not fixed this issue. This is my legacy js: https://tex.poemhub.top/pdfjs-dist/4.4.168/legacy/pdf.worker.min.mjs. Am I missing something? what should I do to fixed this issue?

Firebase Email Auth (passwordless) losing params

This have my custom domain -> mywebsite.com

I go to firebase and create a dynamic link, link preview is like this -> https://mywebsite.page.link/rv3P

My deep link URL is -> https://mywebsite.com

Now i have a react app. In there my action code settings are something like this

const actionCodeSettings = {
      url: "https://mywebsite.page.link/rv3P",
      handleCodeInApp: true,
      iOS: {
        bundleId: "com.org.mobileapp.mywebsite",
      },
      android: {
        packageName: "com.org.services.mywebsite",
        installApp: true,
        minimumVersion: "12",
      },
      dynamicLinkDomain: "mywebsite.page.link",
};

So what’s happening is that upon sending a request to sendSignInLinkToEmail, i get an email on mail i input. On my mail is the correct link that has the OOB code and everything. Now the firebase docs say to check for the window.location.href. The main issue is that once i click the link, i get redirected 3-4 times, from mywebsite.page.link (with oob code) to my firebase domain (with oob code) back to mywebsite.page.link (with oob code) and then finally to https://mywebsite.com where i lose all the params and it’s just the home page of my app. I need those params to log in my users.

Could it be some react routing issue or is firebase redirecting me to my deeplink for some reason?

I have tried going over the react routes to see if there are any redirections and also gone over the firebase console dynamic link multiple times. All seems good to me. Don’t understand what’s causing this redirection

Prevent javascript counter from resetting

I’ve got a javascript counter on a textbox so I can count down the number of characters are left before a field in a table is full. Also, a second counter that counts down before the user runs out of characters that will fit in an email:

<script type="text/javascript">

    function textCounter(field, maxlimit, label, label2) {
        if (field.value.length > maxlimit)
            field.value = field.value.substring(0, maxlimit);
        else {

            label.innerHTML = maxlimit - field.value.length;
        }
        if (field.value.length > maxlimit - 500) {
            label.style.color = "#FF0000";
            label2.style.color = "#FF0000";
        }
        else {
            label.style.color = "#000000";
            label2.style.color = "#000000";
        }
    }

    function textCounter2(field, maxlimit, label, label2) {
        if (field.value.length > maxlimit)
        //  field.value = field.value.substring(0, maxlimit);
        field.value = field.value;
        else {

            label.innerHTML = maxlimit - field.value.length;
        }
        if (field.value.length > maxlimit - 200) {
            label.style.color = "#FF0000";
            label2.style.color = "#FF0000";
        }
        else {
            label.style.color = "#000000";
            label2.style.color = "#000000";
        }
    }

</script>

These are the textbox and counter fields in the ASP page:

<asp:Panel ID="Panel_Employee_Follow_Up" runat="server" Visible="false">
   <table style="width: 100%;">
      <tr>
         <td>
            <asp:TextBox ID="TextBox_Answer" runat="server" Width="600px" MaxLength="3000" Height="120px" onkeydown="textCounter(TextBox_Answer, 3000, Label_Answer_Char_Count, Label_Answer_Char_Remaining);textCounter2(TextBox_Answer, 865, Label_Answer_Char_Count2, Label_Answer_Char_Remaining2);" onkeyup="textCounter(TextBox_Answer, 3000, Label_Answer_Char_Count, Label_Answer_Char_Remaining);textCounter2(TextBox_Answer, 865, Label_Answer_Char_Count2, Label_Answer_Char_Remaining2);" TextMode="MultiLine">
            </asp:TextBox>
            <br />
            <asp:Label ID="Label_Answer_Char_Count" runat="server" Text="3000"></asp:Label>
            <asp:Label ID="Label_Answer_Char_Remaining" runat="server" Text="characters remaining"></asp:Label> : 
            <asp:Label ID="Label_Answer_Char_Count2" runat="server" Text="865"></asp:Label> 
            <asp:Label ID="Label_Answer_Char_Remaining2" runat="server" Text="characters remaining for email"></asp:Label>
            <br />
         </td>
      </tr>
   </table>
</asp:Panel>

What’s happening is, when a user clicks off the textbox, the counter is getting reset. Presumably because of a postback? There are a number of other fields on this form, but I narrowed down the code to just the ones directly relevant to the question. For example, the user typically fills in this textbox and then clicks a button to generate an email.
After the button has been clicked, the counters reset, and I need to prevent them from resetting. I’m not sure if this requires preventing a postback or storing the counter numbers in a session variable. Can anyone offer some guidance on how to prevent the counters from resetting, or how/when I’d write them to a session variable?