Mongoose: Displaying data with ObjectID (or populate)

I am writing a MERN web application. This particular page is focused on recording demerits that have been accrued by students. I have many different models that interact with each other, but in this case I need the following to interact:

const demeritReportInstanceSchema = new mongoose.Schema({
    user : {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
...
})
const userSchema = new mongoose.Schema({
...
    fName: {
        type: String,
        required: true
    },
    lName: {
        type: String,
        required: true
    },
...
})

whereas when the table is displayed, it currently looks like this:

user offenseDate period infractionCode punishingOfficial
(this is a user ObjectID) 65c5480f6b1bcdbcee2491aa Feb 2, 2024 1 another objectID another user ObjectID

I need it it look like:

user offenseDate period infractionCode punishingOfficial
lName, fName Feb 2, 2024 1 M11012 lName, fName

I have been following this tutorial: https://www.youtube.com/watch?v=CvCiNeLnZ00&t=12778s&ab_channel=DaveGray (ref: chapter 7) in which Dave has a Note and User model (backend) like the following:

const noteSchema = new mongoose.Schema({
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User'
        },
...
})
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
})

that displays the username in a similar table as what I have (frontend) by:

Note.js

        return (
            <tr className="table__row">
                ...
                <td className="table__cell note__username">{note.username}</td>

                ...
            </tr>
        )

NotesList.js

    if (isSuccess) {
        const { ids } = notes

        const tableContent = ids?.length
            ? ids.map(noteId => <Note key={noteId} noteId={noteId} />)
            : null

        content = (
            <table className="table table--notes">
                <thead className="table__thead">
                <tr>
                    ...
                    <th scope="col" className="table__th note__username">Owner</th>
                    ...
                </tr>
                </thead>
                <tbody>
                {tableContent}
                </tbody>
            </table>
        )
    }

Any help would be greatly appreciated.

Using {demerit.user} provides me with the ID of the user as displayed above. Using {demerit.user.fName}, {demerit.user.lName} provides me with ” , ” in the cell of the table, and does not return its attributes.
I have been examining how to use Model.populate from Mongoose: https://mongoosejs.com/docs/populate.html but I do not know where I would place populating queries – in the frontend, or the backend with the model?

How to use UTC + 6 hrs instead of browser time?

Ok, I solved everything so far and my script is working. Because im a real beginner and actually quite happe with what I was able to resolve, some of it with help of you guys, I am at a point where my knowledge isn’t enough anymore and I googled the UTC functions in java script but to be honest, I don’t understand a word… Now here is the script….

     var imgElement = document.createElement("img");
     var time = new Date().getHours();



   if (time >= 00 && time <= 04) {
     $(".open").show();
     $(".closed").hide();
     imgElement.src = "https://www.starhit1fm.com/images/covers/musicnonstop.jpg";
     imgEeight = 70;
     imgElement.width = 70;
     // the image to a container div
     var container = document.getElementById("imageContainer");
     container.appendChild(imgElement);
     var actshow = "Music Non Stop<br>We get you through the night!"
     document.getElementById("showon").innerHTML=actshow;
    }else if (time >= 05 && time <= 05) {
     $(".open").show();
     $(".closed").hide();
     imgElement.src = "https://www.starhit1fm.com/images/covers/morning.jpg";
     imgEeight = 70;
     imgElement.width = 70;
     // the image to a container div
     var container = document.getElementById("imageContainer");
     container.appendChild(imgElement);
     var actshow = "Good Moring<br>Program starts at 6 AM"
     document.getElementById("showon").innerHTML=actshow;
    }

Since this is for a radio station, its crucial that the shows appear in the browser on realtime. It doesnt help if a user loads the website, he has local 10 am and in my zone its 4 in the morning, the website would show there is a show on, but of course its not. Now to resolve this my idea was: getting the UTC time instead and deduct 6 hrs. and use the result to display, that would be than my time here and it would be independent from the browser. Can anyone help with this?

Object.assign vs. assignment operator (i.e. = ) for React components

Simple question: I have read a couple of answers such as this on the differences between Object.assign and the assignment operator (i.e. =) and understand all the points brought up such as that the first copies the object while the latter simply assigns the address.

I want to make a decision on which one to use and would like to know what the implications are for React components as I have seen it being done both ways. Is one an antipattern, in the context of React components, which I should not be considering?

And a related question is, is it an acceptable practice to assign to a property of a property i.e.

PageSection.Header.CloseButton = CloseButton

Cannot import ESM modules when modifying require.extensions

TL;DR

How to require (or import) Native ESM modules while using a require hook like require.extensions.

Note: I do know that require.extensions is deprecated and is not recommended to modify, but as ts-node does, I am using this as a part of a temporary workaround.

Goal

I want to dynamic import a configuration file, jiwon.config.ts, which should import other JS/TS extensions successfully.

Restrictions

I cannot use other dependencies like webpack or esbuild to bundle and resolve the imports.
The only option is to use SWC.

Work Flow

  1. importConfig()
  2. looks for jiwon.config.ts, exists
  3. REGISTER REQUIRE HOOK
  4. readFile() the config
  5. SWC transform the code
  6. writeFile() the config as .js
  7. dynamic import jiwon.config.js

REGISTER REQUIRE HOOK

Why? To not bundle and do fewer operations on resolving the config file. Especially utilizing the high performance of SWC.

import { transformSync, type Options } from '@swc/core'

const originalJsHandler = require.extensions['.js']
const transformableExtensions = ['.ts', '.cts', '.mts', '.cjs', '.mjs']
const swcOptions: Options = {
    jsc: {
      target: 'es5',
      parser: {
        syntax: 'typescript',
      },
    },
    module: {
      type: 'commonjs',
    },
    isModule: 'unknown',
  }

function registerSWCTransform(swcOptions: Options, isESM: boolean) {
  // if (isESM) {
  // TODO: handle ESM
  // }

  for (const ext of transformableExtensions) {
    require.extensions[ext] = function (m: any, originalFileName) {
      const _compile = m._compile

      m._compile = function (code: string, filename: string) {
        const swc = transformSync(code, swcOptions)
        return _compile.call(this, swc.code, filename)
      }

      return originalJsHandler(m, originalFileName)
    }
  }
}

Current Status

By doing so, I’ve achieved to cover 90% of the expected & edge cases of resolving the config file.
The only thing that I am struggling with is:

  1. On the Native ESM project (package.json type: module), import the .js (ESM) file.
  2. On the CJS project, import the Native ESM package(also, .js).

They both have in common that the format is ESM but the extension is .js.

As I tried to overwrite the require.extensions['.js'], threw an error during the process of importing other .js files.

Requesting for Help

If you…

  1. know how to resolve requiring Native ESM .js file with the current status
  2. can suggest other ways to achieve the current goal than to register the require hook

please share your expertise and insights, will be very grateful for your help.

Node.js version

{
  node: '18.17.0',
  acorn: '8.8.2',
  ada: '2.5.0',
  ares: '1.19.1',
  brotli: '1.0.9',
  cldr: '43.0',
  icu: '73.1',
  llhttp: '6.0.11',
  modules: '108',
  napi: '9',
  nghttp2: '1.52.0',
  nghttp3: '0.7.0',
  ngtcp2: '0.8.1',
  openssl: '3.0.9+quic',
  simdutf: '3.2.12',
  tz: '2023c',
  undici: '5.22.1',
  unicode: '15.0',
  uv: '1.44.2',
  uvwasi: '0.0.18',
  v8: '10.2.154.26-node.26',
  zlib: '1.2.13.1-motley'
}

Example code

See above.

Operating system

Darwin MacBook-Pro.local 23.1.0 Darwin Kernel Version 23.1.0: Mon Oct  9 21:32:11 PDT 2023; root:xnu-10002.41.9~7/RELEASE_ARM64_T6030 arm64

Scope

Custom compiling through modifying require.extensions.

Module and version

Not applicable.

  1. require.extensions['.js']
  2. createRequire
  3. compile as ESM
  4. ALL of the above with testing with module.parent.filename, module.filename, etc.

Password in apps script for Google Sheets

I’m in charge of making restricted access to a Google Sheets file and all the sheets within it.

My code works but when the user clicks outside the password box, the password box closes and the script stops running so the password is no longer asked for until the file is closed and reopened.

Help to keep the script running always, even if there are sequence errors, until the password is entered. Thank you.

function contrasena() {
  let ui = SpreadsheetApp.getUi() 
  var codigoCorrecto = "Centro Victoria" 
  var guardarIntento = "" 

  while (guardarIntento != codigoCorrecto) {
    guardarIntento = ui.prompt("Por favor ingrese la contraseña").getResponseText();
  } 
  ui.alert("Contraseña Confirmada");
}    

In another onOpen function I created the initializer.Thank you very much in advance

How to make a browser extension open new web page and put text in form

I want to make a browser extension so the user can select some text and be presented with an option which, if they click it, opens google translate web page with the selected text in the input field and the ‘Translate’ button activated so the translation is now in the appropriate field.

I have not made a browser extension before but have some html and javascript knowledge.

This is an initial query because I want to start coding it with a feasible approach in mind.

When using react to make web (sites, pages or applications) how do you decide between JavaScript, TypeScript or JavaScriptXML

So the thing is, I have completed a design of my portfolio and an eCommerce website using Figma and recently pick up React and Tailwind using Vite. I have no problem with basic JavaScript. But what I want to know is how do you decide which to use between basic JavaScript .js, JavascriptXML .jsx and TypeScript .ts. Most React tutorials using Vite use .jsx what I understand is that .jsx was designed or introduced to solve the problem of .js not being able to run in an HTML template and .ts is advanced .js that is preferred by web developers because you don’t get bugs or errors when deploying the website or application.
But how and when do you decide when to use what I’m confused.

Also are there best practices to which languages you should, use and which are a good and bad match. Any explanation involving React, JavaScript, TypeScript, JSX, HTML and Node will be highly apricated. Anything will be appreciated, no matter how insignificant you think it may be, it will aid me on my web development journey.

Export data in html webapp from tg_bot

markup.add(KeyboardButton("Открыть магазин", web_app=WebAppInfo(url="https://<nickname>.github.io/")))
Открываю web_app через кнопку, нужно, чтобы в html отображались объекты, лежащие в БД, чтобы можно было их передать и вывести на страницу, как это сделать? Обшарил весь интернет, нигде не написано, подскажите пожалуйста

Открывал атрибуты WebAppInfo, однако туда никаких данных передать нельзя

No Interactions when dynamically adding items to flowbite accordion component

So I am using flowbite and vanilla javascript to do a UI.

I am dynamically adding items to an accordion by loading them (via PHP) from a DB. So the PHP script returns an id, section name and section text as JSON.

Now this script then generates the HTML to fit in the accordion container:

document.addEventListener('DOMContentLoaded', function() {
    fetch('src/php/getExecSummary.php')
    .then(response => response.json())
    .then(data => {
        const accordionContainer = document.getElementById('accordionExecSummary');
        
        data.forEach((section, index) => {
            const isOpen = index === 0 ? true : false;
            const sectionElement = `
                <h2 id="accordion-heading-${index}">
                    <button type="button" data-accordion-target="#accordion-collapse-body-${index}" class="flex items-center justify-between w-full p-5 font-medium text-left border-b border-gray-200" aria-expanded="${isOpen}" aria-controls="accordion-collapse-body-${index}">
                        <span>${section.SectionName}</span>
                        <!-- Include accordion icon here -->
                    </button>
                </h2>
                <div id="accordion-collapse-body-${index}" class="${isOpen ? '' : 'hidden'}" aria-labelledby="accordion-heading-${index}">
                    <div class="p-5 border-b border-gray-200">
                        <textarea class="w-full h-32 p-2 border border-gray-300">${section.SectionText}</textarea>
                    </div>
                </div>
            `;            
            accordionContainer.innerHTML += sectionElement;
        });

    })
    .catch(error => console.error('Error loading executive summary sections:', error));
});

So I get the sections and the sections are named from data back from the DB but I cannot interact with the accordion; so clicking the section name doesn’t expand/collapse the section. No errors in the console and cant find any refresh() method or anything like that.

Not sure what else I can do?

Issues in loading a .glb file in a web worker offscreencanvas using Three.js

I have been trying to use GLTFLoader from Three.js to load a model into an offScreenCanvas. This is what I am currently trying:

import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
const loader = new GLTFLoader();
const draco = new DRACOLoader();
draco.setDecoderConfig({ type: "js" });
draco.setDecoderPath("https://www.gstatic.com/draco/v1/decoders/");

loader.setDRACOLoader(draco);

const res = await fetch("https://static.motionmix.ai/web/female.glb");
  if (!res.ok) return;
  const arrayBuffer = await res.arrayBuffer();
  loader.parse(
    arrayBuffer,
    "",
    (gltf) => {
      console.log("gltf loaded is", gltf);
    },
    (error) => {
      console.log("error", error);
    }
  );

Neither the onload nor the onerror callback gets triggered. I am very new to using web workers in javascript. But I am completely at a loss here.

I have tried to use loader.load as well, but to no avail. it seems like the callbacks just won’t get called. Where am I going wrong?

Iframe URL that changes frequently

I’d like to iframe an interactive map whose url changes very frequently. The url changes because it takes into account parameters for the map (like coordinates, activated layers, zoom level etc.). As soon as you navigate on the map, the url changes. I’d like to be able to share the parent page with the map in iframe, taking these url changes into account.

The url with his parameter values looks like this: https://kartenn.region-bretagne.fr/kartoviz/?x=-179589&y=6124999&z=12.603072424400471&l=lycee&lb=osm1&config=demo/print.xml

The parameter values in this url are: x=-179589&y=6124999&z=12.603072424400471&l=lycee&lb=osm1

Is it possible to pass these parameter values to the url of the parent page? Or is there another possibility?

Ideally, I’d like to avoid having to host the page every time the url changes.

How do I make my code loop through this array?

I am trying to make a color changer, I want the program to loop through the array, change the color one by one with every click, then update the color-code class to the name of the array, I haven’t implemented this yet because I want to tackle this initial problem first. So far, It only changes the color to the last index.

const colorArray = ["blue", "green", "red", "orange", "violet", "indigo", "yellow", "white", "pink", "black"];

function changeColor() {
    const body = document.querySelector('body');
    const bodyColor = body.style.backgroundColor;
    const colorCode = document.querySelector('color-code');
    const button = document.querySelector('button');

    button.addEventListener('click', function () {
        for(let i = 0; i < colorArray.length; i++) {
            body.style.backgroundColor = colorArray[i];
        }
    

    })
}

changeColor();

I tried using a for loop, I’m not quite sure it’s the right way to go.

API Gateway – CORS error with query string

I have a GET request through API gateway that works when I test within the API Gateway console, so it seems my Lambda function is okay.

All my other methods and resources are working within the API, so I’m wondering if the query string parameter is causing the CORS issue. I’ve enabled CORS for the GET method via the API Gateway console. Am I barking up the wrong tree to think it’s the query string? What other areas should I look into to resolve the CORS error? Enabling CORS has resolved the issue before. The error is:

Access to fetch at 'myAPIURL' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

The API call is as follows in my frontend:

fetchInvoices(strParam){
    const returnedData = null;
    const url = invokeURL + encodeURIComponent("invoicess?invYear=" + strParam);
    fetch(url, { headers: { "Authorization": token } })
        .then(response => { 
        return response.json() 
    })
    .then(jsonData => {
        returnedData = jsonData;
    })
    .catch(e => {
        console.log(e)
    })
    return returnedData
}

regex validation for only specific characters in Javascript

I am trying to create regular expression for specific code, here are the requirements

  1. Length should be 13
  2. First letter starts with X
  3. Next letters A-Z and 0-9 should accept
  4. Only capital letters

Ex : XAABBCC88EE00

I created this expression ^[X]{1}-[a-zA-Z0-9]{12}$, But it’s not working. How Can I create one for this