How to find where is error in this loggly record

can someone help me with reading the loggly records, I have problems with reading the message “undefined is not an object (evaluating ‘a.L’)” since I don’t have a.L anywhere in my code, I assume it’s rendered html or some script but I can’t to find exactly where the problem is.
I think the error was thrown by window.onerror

enter image description here

i tried to find some code in the scripts i uploaded but no luck in finding it

Add and delete class out of index Javascript

So I have this code that delete me some classes every 8000 milliseconds. But I want to clear the interval everytime it delete that class and start over when that class exist again.

So here’s an example

<div id="oneTab" class='secondaryNav activeTab'></div>

I want to delete the “activeTab” class after 8000 milliseconds and reset and stop the timer then only when the class exists again to start the timer again.

  var count = 1;
 var timer = 8000;

function transition() {
    if(count == 1) {
        $('.secondaryNav').removeClass('activeTab');
        $('.navLink').removeClass('active');
         count = 2;
    } else if(count == 2) {
        $('.secondaryNav').removeClass('activeTab');
        $('.navLink').removeClass('active');
         count = 3;
    } else if(count == 3) {
        $('.secondaryNav').removeClass('activeTab');
        $('.navLink').removeClass('active');
        count = 1;
    }
}
    setInterval(transition, timer);

Or it might be an easier way with JS to delete a class a add another when clicking outside the div or link

function openTab(evt, tabName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("secondaryNav");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].classList.remove("activeTab");
  }
  tablinks = document.getElementsByClassName("navLink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks.className = tablinks[i].classList.remove("active");
  }
  document.getElementById(tabName).classList.add("activeTab");
  evt.currentTarget.className += " active";
  tabcontent[i].classList.remove("activeTab");
}

I have this code that opens different tab depending on the link but I want that tab to disappear if I click outside the tab or everywhere else except his link.

I tried making some clearInterval(timer) methods, but I couldn’t make it.
On the JS code I tried adding a class “fadedTab” but it adds that class to all tabs except the activeTab one and I only want to add it to the last tab for like 3-4 seconds that remove that class.

Cannot find module ‘stripe’ during firebase deploy JavaScript functions in Flutter app

I have added two firebase functions to my flutter app to implement Stripe.

const functions = require("firebase-functions");
const stripe = require("stripe")(functions.config().stripe.testKey)

const calculateOrderAmount = (items) => {
    prices = [];
    catalog = [
        { 'id': '0', 'price': 3.99, },
        { 'id': '1', 'price': 7.99, },
        { 'id': '2', 'price': 9.99, },
    ];

    items.array.forEach(item => {
        price = catalog.find(x => x.id == item.id).price;
        prices.push(price);
    });

    return parseInt(prices.reduce((a, b) => a + b) * 100);
}

const generateResponse = function (intent) {
    switch (intent.status) {
        case 'requires_action':
            return {
                clientSecret: intent.clientSecret,
                requiresAction: true,
                status: intent.status,
            }
        case 'requires_payment_method':
            return {
                'error': 'Your card was denied, please provide a new payment method',
            };
        case 'succeded':
            console.log('Payment succeded')
            return {
                clientSecret: intent.clientSecret,
                status: intent.status,
            };
    }
    return {
        error: 'Failed'
    };
}

exports.StripePayEndpointMethodId = functions.https.onRequest(async (req, res) => {
    const { paymentMethodId, items, curency: currency, useStripeSdk, } = req.body;

    const orderAmount = calculateOrderAmount(items);

    try {
        if (paymentMethodId) {
            const params = {
                amount: orderAmount,
                confirm: true,
                confirmation_method: 'manual',
                currency: currency,
                payment_method: paymentMethodId,
                use_stripe_sdk: useStripeSdk,
            }

            const intent = await stripe.paymentIntents.create(params);
            console.log('Intent: ${intent}');
            return res.send(generateResponse(intent));
        }
        res.sendStatus(400)
    } catch (error) {
        return res.send({ error: error.message });
    }
});

exports.StripePayEndpointIntentId = functions.https.onRequest(async (req, res) => {
    const { paymentIntentId } = req.body;
    try {
        if (paymentIntentId) {
            const intent = await stripe.paymentIntents.confirm(paymentIntentId);
            return res.send(generateResponse(intent));
        }
        return res.sendStatus(400)
    } catch (error) {
        return res.send({ error: error.message })
    }
});

However when I run the command firebase deploy --only functions it shows me an error. Here is the full log:

=== Deploying to 'jimv01'...

i  deploying functions
✔  functions: Finished running predeploy script.
i  functions: preparing codebase default for deployment
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
i  artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔  artifactregistry: required API artifactregistry.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
✔  functions: required API cloudbuild.googleapis.com is enabled
i  functions: Loading and analyzing source code for codebase default to determine what to deploy
Serving at port 8950

i  functions: preparing functions directory for uploading...
i  functions: packaged /Users/fscozano/Desktop/GymPT_0.2/server/functions (75.05 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: updating Node.js 18 (1st Gen) function StripePayEndpointMethodId(us-central1)...
i  functions: updating Node.js 18 (1st Gen) function StripePayEndpointIntentId(us-central1)...
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Provided module can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'stripe'
Require stack:
- /workspace/index.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/loader.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/main.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
    at Module._load (node:internal/modules/cjs/loader:975:27)
    at Module.require (node:internal/modules/cjs/loader:1225:19)
    at require (node:internal/modules/helpers:177:18)
    at Object.<anonymous> (/workspace/index.js:2:16)
    at Module._compile (node:internal/modules/cjs/loader:1356:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1414:10)
    at Module.load (node:internal/modules/cjs/loader:1197:32)
    at Module._load (node:internal/modules/cjs/loader:1013:12)
    at Module.require (node:internal/modules/cjs/loader:1225:19)
Could not load the function, shutting down.. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Provided module can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'stripe'
Require stack:
- /workspace/index.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/loader.js
- /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/main.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
    at Module._load (node:internal/modules/cjs/loader:975:27)
    at Module.require (node:internal/modules/cjs/loader:1225:19)
    at require (node:internal/modules/helpers:177:18)
    at Object.<anonymous> (/workspace/index.js:2:16)
    at Module._compile (node:internal/modules/cjs/loader:1356:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1414:10)
    at Module.load (node:internal/modules/cjs/loader:1197:32)
    at Module._load (node:internal/modules/cjs/loader:1013:12)
    at Module.require (node:internal/modules/cjs/loader:1225:19)
Could not load the function, shutting down.. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.

Functions deploy had errors with the following functions:
        StripePayEndpointIntentId(us-central1)
        StripePayEndpointMethodId(us-central1)
i  functions: cleaning up build files...
⚠  functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/gcr/images/jimv01/us/gcf
Error: There was an error deploying functions:
- Error Failed to update function StripePayEndpointMethodId in region us-central1
- Error Failed to update function StripePayEndpointIntentId in region us-central1

Here is also the package.json file:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "18"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^11.8.0",
    "firebase-functions": "^4.3.1"
  },
  "devDependencies": {
    "eslint": "^8.15.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^3.1.0"
  },
  "private": true
}

From the log, I assume that the problem is that it can’t find the stripe module and, as you can see, the stripe dependency doesn’t show even though I added it through the command npm install stripe --save. For this reason, I tried adding it manually:

"dependencies": {
    "firebase-admin": "^11.8.0",
    "firebase-functions": "^4.3.1",
    "stripe": "^6.28.0"
  },

However, it shows another error:

=== Deploying to 'jimv01'...

i  deploying functions
✔  functions: Finished running predeploy script.
i  functions: preparing codebase default for deployment
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
i  artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  artifactregistry: required API artifactregistry.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
i  functions: Loading and analyzing source code for codebase default to determine what to deploy
Serving at port 8640

i  functions: preparing functions directory for uploading...
i  functions: packaged /Users/fscozano/Desktop/GymPT_0.2/server/functions (75.06 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: updating Node.js 18 (1st Gen) function StripePayEndpointMethodId(us-central1)...
i  functions: updating Node.js 18 (1st Gen) function StripePayEndpointIntentId(us-central1)...
Build failed: npm ERR! code EUSAGE
npm ERR! 
npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR! 
npm ERR! Missing: [email protected] from lock file
npm ERR! 
npm ERR! Clean install a project
npm ERR! 
npm ERR! Usage:
npm ERR! npm ci
npm ERR! 
npm ERR! Options:
npm ERR! [--install-strategy <hoisted|nested|shallow|linked>] [--legacy-bundling]
npm ERR! [--global-style] [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
npm ERR! [--include <prod|dev|optional|peer> [--include <prod|dev|optional|peer> ...]]
npm ERR! [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit]
npm ERR! [--no-bin-links] [--no-fund] [--dry-run]
npm ERR! [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
npm ERR! [-ws|--workspaces] [--include-workspace-root] [--install-links]
npm ERR! 
npm ERR! aliases: clean-install, ic, install-clean, isntall-clean
npm ERR! 
npm ERR! Run "npm help ci" for more info

npm ERR! A complete log of this run can be found in: /www-data-home/.npm/_logs/2024-03-17T19_44_48_688Z-debug-0.log; Error ID: beaf8772
Build failed: npm ERR! code EUSAGE
npm ERR! 
npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR! 
npm ERR! Missing: [email protected] from lock file
npm ERR! 
npm ERR! Clean install a project
npm ERR! 
npm ERR! Usage:
npm ERR! npm ci
npm ERR! 
npm ERR! Options:
npm ERR! [--install-strategy <hoisted|nested|shallow|linked>] [--legacy-bundling]
npm ERR! [--global-style] [--omit <dev|optional|peer> [--omit <dev|optional|peer> ...]]
npm ERR! [--include <prod|dev|optional|peer> [--include <prod|dev|optional|peer> ...]]
npm ERR! [--strict-peer-deps] [--foreground-scripts] [--ignore-scripts] [--no-audit]
npm ERR! [--no-bin-links] [--no-fund] [--dry-run]
npm ERR! [-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
npm ERR! [-ws|--workspaces] [--include-workspace-root] [--install-links]
npm ERR! 
npm ERR! aliases: clean-install, ic, install-clean, isntall-clean
npm ERR! 
npm ERR! Run "npm help ci" for more info

npm ERR! A complete log of this run can be found in: /www-data-home/.npm/_logs/2024-03-17T19_45_17_967Z-debug-0.log; Error ID: beaf8772

Functions deploy had errors with the following functions:
        StripePayEndpointIntentId(us-central1)
        StripePayEndpointMethodId(us-central1)
i  functions: cleaning up build files...
⚠  functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at https://console.cloud.google.com/gcr/images/jimv01/us/gcf
Error: There was an error deploying functions:
- Error Failed to update function StripePayEndpointMethodId in region us-central1
- Error Failed to update function StripePayEndpointIntentId in region us-central1

Then, I discarded the option of manually adding the stripe module. Moreover, when I faced the first issue, the functions were loaded on firebase but with an error, so they are there but I can’t use them.

Failed to load resource: the server responded with a status of 500 (Internal Server Error) , Unexpected token ‘P’, “Proxy erro”… is not valid JSON

[ i have question in the end]

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
App.jsx:18 Error fetching todos: SyntaxError: Unexpected token ‘P’, “Proxy erro”… is not valid JSON

this is the error statement

what I understand is that its a internal server error in my code

this is the route.js


const express = require("express")

const router = express.Router();

// // get todo
router.get("/todos",(req,res)=>{
      res.status(200).json({mssg:"GET REQUEST TO /api/todos"})
});


// post todo
router.post("/todos",(req,res)=>{
      res.status(201).json({mssg:"GET REQUEST TO /api/todos"})
});



//delete todo
router.delete("/todos/:id",(req,res)=>
{
    res.status(200).json({mssg:"DELETE REQUEST TO /api/todos/:id"});
});


//put todoo

router.put("/todos/:id",(req,res)=>{
    res.status(200).json({mssg:"PUT REQUEST TO /api/todos/:id"});
});

module.exports =router;

this is part of client folder


import { useEffect } from "react";

 

export default  function App() {

  useEffect(()=> {
      async function getTodos() {
        const res = await fetch("/api/todos");
        const todos = await res.json();

        console.log(todos);
      }
      getTodos();

  },[])


  return (
  <main className="container">

    <h1>The to-do</h1>

  </main>
  ); 
}
 

and we added a proxy in packages.json to bypass the coros policy and shorten the whole http link
to /api/todos to allow it to change the port

any thing more to add

QUESTIONS

  1. why am i getting a p token error
    2)if there error is due to lack of fundamental knowledge please enlighten me

i tried the above while following a course on yt.

my image is displaying as a box not a hexagon

I want to make these hexagons in a grid-like pattern, but they are not sized properly and dont pack as tightly as I would like because they are box sprites. I checked the PNG in my file explorer and it does not have any background, it is just the hexagons.

hexagons

document.getElementById("Button1").addEventListener("click", myFunction);

function myFunction() {
  createCanvas();
}

function drawHexagon(x, y, scale) {
  const c = document.getElementById("hexagonCanvas");
  const ctx = c.getContext("2d");
  const img = document.getElementById("whex");
  ctx.drawImage(img, x, y, 4 * scale / Math.sqrt(3), scale);
}

function createCanvas() {
  let n = 100;
  let hex = new Array(n);
  for (let i = 0; i < n; i++) {
    hex[i] = new Array(n);
    for (let j = 0; j < n; j++) {
      hex[i][j] = false;
      let scale = 100;
      let y = 2 * scale * i + scale;
      let x = 2 * scale * Math.sqrt(3) * j;
      if (j % 2 == 1) {
        y += scale;
      }
      //console.log(x + " " + y + " " + i + " " + j);
      drawHexagon(x, y, scale);
    }
  }

}
<img src="https://images.vexels.com/media/users/3/139198/isolated/lists/89ce93222bff9f1e4f6195d164d0c8bf-hexagon-shape-stroke-icon.png" id="whex" class="hola">
<canvas id="hexagonCanvas" width="2000" height="2000" style="border:1px solid grey;"></canvas>
<button id="Button1">Try it</button>
<p id="demo"></p>
<script src="hexGame.js"></script>

Passing Cookies as arguments in ElysiaJS

Not sure if this is possible exactly but I wanted to try anyway. I have my Elysia server set up like the following:

server.ts

export const server = new Elysia({
  cookie: {
    secrets: Bun.env.COOKIE_SECRET,
    sign: ["profile"]
  }
})

Then I have this route that executes a function called handleUserRedirect(). This function takes a query parameter (which I have no issue passing) and I want to pass it a cookie so I could change the cookie’s value after some receiving some response data within this function.

server.ts

.get("/user-redirect", async ({ query, cookie }) => handleUserRedirect(query.code, cookie.profile), {
    query: t.Object({
      id: t.String(),
    }),
    cookie: t.Cookie({
      profile: t.Object({
        token: t.String(),
        name: t.String(),
      })
    })

  })

handler.ts

export async function handleUserRedirect(id: string, profile: { token: string, name: string }) {
...
// make a get request to an api and receive a response containing some basic user information
const responseData = await response.json();
profile.token = responseData.token;
profile.name = responseData.name;
}

This is the error I get:
Argument of type ‘Cookie<{ name: string; token: string; }>’ is not assignable to parameter of type ‘{ profile: { token: string; name: string; }; }’. Property ‘profile’ is missing in type ‘Cookie<{ name: string; sub: string; }>’ but required in type ‘{ profile: { sub: string; name: string; }; }’.

I have been stuck on this for a while now and have tried using various functions within the Elysia docs such as afterHandle where I tried returning just the response and tried to set the cookies in my server based on that but that didn’t work either. The only solution I have been able to come up with thus far is using Elysia’s store instead of cookies.

E4979D1925EE3120 [closed]

$ sudo fastboot devices
01234567 fastboot
git fetch https://android.googlesource.com/platform/packages/providers/DownloadProvider refs/changes/49/3000849/1 && git checkout -b change-3000849 FETCH_HEADhttps://issuetracker.google.com/issues?q=id%3A(254502852%7C199453223%7C67020813%7C37106547%7C37126897%7C37587060%7C37628425%7C37878343%7C62046336%7C62449759%7C62479045%7C62497586%7C63152228%7C63171090%7C63407983%7C63619041%7C63693073%7C63959789%7C64043132%7C64282262%7C64380426%7C64580434%7C72119476%7C75986381%7C76404688)

No puedo descargar android

I get undefined when I am using js to create a-entity with aframe component

I am trying to add some objects through a-entity based on a given location. the problem is setAttribute is not working because when I call getAttribute, it return “undefined”. even geometry and material.. by the way I hardcoded an entity with html tag and it works correctly.
I thought I have to wait for a-scene to load completely but its not working either.
can anyone let me know what is the problem? I think I am missing something but I do not know what it is.

<script>

console.log("0");
AFRAME.registerComponent('gps-coins', {
  init: function () {
console.log("started1");

    for (var i = 0; i < 5; i++) {

      var coinEntity = document.createElement('a-entity');

      coinEntity.setAttribute('geometry', 'primitive: cylinder; radius: 5; height: 1'); // Adjust size
      coinEntity.setAttribute('material', 'color:green'); // Coin color
      coinEntity.setAttribute('rotation', '0 90 90'); 
      coinEntity.setAttribute('position', '5 5 5'); 
    console.log(coinEntity.getAttribute('geometry'));   
    console.log(coinEntity.getAttribute('material'));   

      // Append the coin to the scene
      this.el.appendChild(coinEntity);


    }
  }
});

console.log("very end");
</script>

I want to create 10 coin in the a-scene and also set some attribute to them but when I call getAttribute, I get undefined.

How to write a regex to capture a number surrounded by other characters?

export interface ValueParserResult {
  value: number, 
  error: string
}

interface subParseResult {
  result: (string | number) [], 
  error: string
}

class ValueParser {

  parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParserResult {
    const result: ValueParserResult = { value: 0, error: "" }
  
    const numberRe: RegExp = /([^|\(||/|/\-|-|\*|\*\-|+|\^])+([0-9.]*)([$|(|)|/|/-|-|*|*-|+|])+/g;
          
    const eqParse = eq.split(" ").join('');
    eqParse.replace(numberRe, (matched) => {
      return " ," + matched;
    })
    
    console.log(eqParse)
    return result;

  }
}

const vp = new ValueParser();
const values = {a: 22, b:-10, c: 5}

const eq = "123/456*82*(a+b/c)"

vp.parse(eq, values)

This captures the entire eqParse string and puts a space comma in front of it. I want to put the comma space before each value and not capture the strings before and after.

event.currentTarget.parentNode.remove(); not working

I am trying to learn stuff I was used to doing in jQuery in plain JavaScript.

I have an example I found on the internet to solve, which gave me a hard time.

I am trying to remove the parent div. single on click on the button. remove.

Here is the code;

<div class="row" id="showAward">

</div>
<div class="w-100 text-center">
    <a id="add" class="bg-primary text-white px-3 py-2 rounded-circle cursor-pointer">
        <i class="fa-solid fa-plus"></i>
    </a>
</div>

<script>
    let count = 0;

    document.addEventListener('click', function(event) {
        if (event.target.id === 'add') {
            count++;
            addAward(count);
        }
        if (event.target.classList.contains('delete')) {
            event.currentTarget.parentNode.remove();
        }
    });
    function addAward(number) {
        let html = `<div class="col-lg-4 mb-3 position-relative">
            <label for="image${number}" class="form-label">image ${number}</label>
            <input type="file" class="form-control" id="image${number}" name="image${number}">
            <a class="delete text-danger cursor-pointer position-absolute end-0 top-0"><i class="fa-solid fa-times"></i></a>
        </div>`;
        document.getElementById('showAward').insertAdjacentHTML('beforeend', html);
    }

</script>

Google reCaptcha errors layering

I’m getting default warning in reCaptcha (This reCaptcha is for…) and when I’m getting another warning they are layering.
Is exist a proppert way to move one of them to the bottom or hide “This reCaptcha is…”?
I’ve tried to hide it with using css and js, but errors inside Iframe so idk
image

Javascript to edit CSS Style

I am having trouble getting my JavaScript code to change the CSS style of my article element. I have this in the opening tag for my article element:
”’

<img id="n1" onmouseover="visible('c1')" src="img/musicnote1.png" alt="Music Note">

”’
and then at the bottom of my body section I have my script tag:
”’

<script>
    function visible(a){
        document.getElementById(a).style.display = initial;
        document.getElementById('default').style.display = none;
    }
</script>

”’
I am trying to make the ‘c1’ article appear and the ‘default’ article disappear when the user hovers over the image. Neither of these actions are working

Validation Chain not working in express validator

const express = require("express");
const router = express.Router();
const User = require("../Models/User");
const { body, validationResult } = require("express-validator");

//post route for registering user(No auth required)
router.post(
  "/",
  [
    body("name", "Name cannot be empty").notEmpty().customSanitizer(value => {
      return escape(value);
    }),
    body("email", "Enter a valid email").isEmail(),
    body(
      "password",
      "Password must be 8characters long. 1 lowercase, 1 uppercase, 2 number and 1 special character is required"
    ).isStrongPassword({
      minLength: 8,
      minLowercase: 1,
      minUppercase: 1,
      minNumbers: 1,
      minSymbols: 1,
    }),
  ],
  async (req, res) => {
    const result = validationResult(req);
    if (result.isEmpty()) {
      //All validations passed
      try {
        const user = User(req.body);
        await user.save();
        res.send(req.body);
      } catch (err) {
        return res.status(400).json({ error: "Email already exists" });
      }
    }
    res.send({ errors: result.array() });
  }
);

module.exports = router;

Here in my express code if I am just using the .notEmpty() method of express-validator with my name field I am not facing any error and it works perfectly fine. But if I use .escape() method along with it, then my express application crashes by giving the following error
node:internal/errors:491
ErrorCaptureStackTrace(err);
^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:400:5)
at ServerResponse.setHeader (node:_http_outgoing:663:11)
at ServerResponse.header (C:Web DevelopmentSwift NotesBackendnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (C:Web DevelopmentSwift NotesBackendnode_modulesexpresslibresponse.js:174:12)
at ServerResponse.json (C:Web DevelopmentSwift NotesBackendnode_modulesexpresslibresponse.js:278:15)
at ServerResponse.send (C:Web DevelopmentSwift NotesBackendnode_modulesexpresslibresponse.js:162:21)
at C:Web DevelopmentSwift NotesBackendRoutesauth.js:37:9
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: ‘ERR_HTTP_HEADERS_SENT’
}

I referred the express-validator documentation and my code is exactly as per their documentation still I don’t know why I am not able to use multiple methods by chaining them. However my works perfectly fine when I use a single method

how to update a field that is an object in mongo db using node js

So I have a schema right now for a users profile and I want to update the media related to that profile and store it mongodb the way we identify a user is through their username as they are unique on the site I tried the push method but it doesn’t seem to work, the profile is found correctly just trying to update the existing field object we don’t want to override what is stored at that object either just add to what is already there.

here is the schema:

const mongoose = require("mongoose");


const medallionProfileSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true,
    unique: false,
  },
  middleName: {
    type: String,
    required: false,
    unique: false,
  },
  lastName: {
    type: String,
    required: true,
    unique: false,
  },
  title: {
    type: String,
    required: false,
    unique: false,
  },
  relationship: {
    type: String,
    required: false,
    unique: false,
  },
  media: {
    title: {
      type: String,
      required: false,
    },
    description: {
      type: String,
      required: false,
    },
    mediaType: {
      type: String,
      required: false,
    },
    mediaLink: {
      type: String,
      required: false,
    },
  },
});

const profileSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  dateCreated: {
    type: Date,
    required: false,
    unique: false,
  },
  bio: String,
  // Add other profile-related fields as needed
  medallionProfile: medallionProfileSchema, // Embed MedallionProfile schema


});


const Profile = mongoose.model("Profile", profileSchema);

module.exports = Profile;

here is the function to carry out the update the req.body params are present and correct:

const uploadProfileMedia = async (req, res) => {
  try {
    // Extract data from the request body
    const { username, title, description, mediaType, mediaLink } = req.body;

    // Find the profile document associated with the provided username
    const profile = await Profile.findOne({ username });
    console.log("profile in uploading media ", profile);

    // If the profile doesn't exist, return an error
    if (!profile) {
      return res.status(404).json({ error: "Profile not found" });
    }

    // Add the new media to the profile
    profile.medallionProfile.media.push({
      title,
      description,
      mediaType,
      mediaLink,
    });

    // Save the updated profile document
    await profile.save();

    // Respond with a success message
    res.status(200).json({ message: "Media uploaded successfully" });
  } catch (error) {
    // Handle errors
    console.error("Error uploading profile media:", error);
    res.status(500).json({ error: "Internal server error" });
  }
};