mongoose findAndUpdate with discriminator

I have several types of products such as phones, laptops, headphones, etc. All of these products in the end result turns out to be you one generalized ProductsModel

ProductsModel

import { Schema, model } from 'mongoose'

export const productsDiscriminatorKey = 'productKind'

const ProductsSchema = new Schema(
    {
        name: { type: String },
    },
    { productsDiscriminatorKey, timestamps: true }
)

export default model('Products', ProductsSchema)

PhoneModel

import mongoose, { Schema } from 'mongoose'

import ProductsModel, { productsDiscriminatorKey } from './ProductsModel.js'

const PhoneSchema = new Schema(
    {
        name: { type: String, required: true },
        price: { type: String, required: true },
        color: { type: String, required: true },
        memory: { type: String, required: true },
        screen: { type: String, required: true },
        fps: { type: String, required: true },
        sim: { type: String, required: true },
        preview: { type: String, required: true },
        images: [{ type: String, required: true }],
        category: {
            type: mongoose.Schema.ObjectId,
            ref: 'Category',
        },
        type: {
            type: mongoose.Schema.ObjectId,
            ref: 'Type',
        },
        count: { type: Number },
    },
    { productsDiscriminatorKey }
)

const PhoneModel = ProductsModel.discriminator('Phones', PhoneSchema)
export default PhoneModel

I implemented the logic of removing products from the database by quantity, rather than the entire model at once. If I use it specifically in the PhoneModel or in another model (not in the ProductsModel), then all the logic works correctly. But as soon as I try to do this from ProductsModel, then it just doesn’t change the count field.

Delete logic

    async delete(req, res) {
        try {
            const { id } = req.params
            const { count } = req.body

            const candidate = await ProductsModel.findById(id)

            if (candidate.count < count) {
                return res.status(500).json({ message: 'More than count in base' })
            }

            if (candidate.count === count || !count) {
                await ProductsModel.findByIdAndDelete(id)
                return res.status(200).json({ message: 'All deleted' })
            }

            if (candidate.count > count) {
                await ProductsModel.findByIdAndUpdate({ _id: id }, { count: candidate.count - count })

                return res.status(200).json({ message: `${count} successfully deleted` })
            }
        } catch (error) {
            return res.status(500).json({ message: 'Server error' })
        }
    }

That is, there is a case when you need to delete not all at once, but a certain amount (count). I implemented this by simply changing the count field using findByIdAndUpdate. But it just doesn’t work out and doesn’t throw out any errors.

Losing return on a Recursion function on HTML JavaScript

I have an object

{
   path: "",
   name: "",
   isFolder: true,
   childs: [
      {
         path: "assets",
         name: "assets",
         isFolder: true,
         childs: [
            {
               path: "assets/img",
               name: "img",
               isFolder: true,
               childs: [
                  {
                     path: "assets/img/logo.png",
                     name: "logo.png",
                     isFolder: false,
                     childs: [],
                  },
               ],
            },
            {
               path: "assets/txt",
               name: "txt",
               isFolder: true,
               childs: [
                  {
                     path: "assets/txt/logo.txt",
                     name: "logo.txt",
                     isFolder: false,
                     childs: [],
                  },
               ],
            },
         ],
      },
   ],
}

I called:

            node = GetDir("assets/img");
            document.getElementById("json").innerHTML = prettyPrintJson.toHtml(node);

which the function look like this

    let targerDir;

    function GetDir(path) {
        return FindNodeByPath(tree, path);
    }

    function FindNodeByPath(node, path) {
        for (let index = 0; index < node.childs.length; index++) {
            c = node.childs[index];
            if (c.path === path) {
                console.log(c)
                targetDir = c;
                return c;
            } else
                FindNodeByPath(c, path)
        }
        // return false;
    }

The result of node become undefined, but the console.log(c) has the correct value.

enter image description here

I saw some said, need to store that somewhere else(i tried to store it to targetDir and it work. But, there is noway to define each var for every access right?)

or stop the loop(?) and i tried add return false; at the end of the function, and it just return false.

what am i doing wrong?

Is there any way to recreate the infinity scroll with content repetation? [closed]

I’m attempting to recreate the layout and functionality of the webpage https://marioecg.com/ or https://unseen.co/world/ type of infinite scroll and draggability using React.js, but I’m unsure of how to go about it. I would appreciate any assistance or guidance on this project. Thank you!

I’m not sure which libraries are used. Will be helpful if similar reference code is available

how a fetch a json site with error with javascript language, on txt file is ok

i have problens with fetch code in javascript, what code is a correct to fetch all body this site –>
https://dogechain.info/api/v1/address/balance/AC8Q9Z4i4sXcbW7TV1jqrjG1JEWMdLyzcy — this site have a balance of one dogechain wallet, is a example, i need this to input on my site the code,
is a json site, please send me a code with echo on body with innerhtml. thank you for attention.

i try with a php site a fetch code with this informations and work, but, on this json site have more tags and i get errors with fetch code and dont work.

Microsoft Clarity logged “script error” JS

I just installed Clarity on a angular website & I manage and I got 100% sessions with JS errors.
I have many errors like undefined functions, null properties & etc.
But i have “script error” that contains 98% of errors. i haven’t any description more for this error.

I watched every records & they have different scenario. How i can debugging and find this bug?

Typescript ternary evaluation [duplicate]

Would like to ask does anyone know how typescript evaluate the below ternary condition

let str = "asd/asd";
let nodeId = null;


console.log(`${str}` + nodeId? "a":"b"); // Output "a" instead of "asd/asda"

The output i try in typescript editor it show as “a”. Wouldn’t it be “asd/asda”?

Once i enclose the condition like this

let str = "asd/asd";
let nodeId = null;


console.log(`${str}` + (nodeId? "a":"b")); // Output "asd/asda"

It display as “asd/asda”

What does it mean to have something highlighted in red in sublime text? [closed]

screenshot

I’m not sure why the start of my note is highlighted in red. In the screen shot shown above “Font Awesome” is just meant to be a note. however < is highlighted in red and rather than being white, the whole note is purple. This is a copied and pasted code but I also attempted to enter it in by hand and the same thing still happens. I’m still pretty new to the coding world but in the month or so that I’ve been dabbling, I have never seen this red highlighted item. Could anyone possibly tell me what it means? Does it matter if it is there, and if so, how to I remove it?

Hide image if another one is opened, vice versa

I’m have code for 2 images (Image1, Image2) that both open if 2 other images are clicked, with onclick and a java part at the end, like so:

<table style="whatever">
    <tbody>
        <tr style="whatever"">

            <td><a href="link to game1 when the image is clicked" alt="Game1" target="blank" onclick="AfficherCacher('Image1')"> <img src="the image clicked to open Game1+Image1.jpg" width="1689" height="955" class="img-fluid atto_image_button_text-bottom"></a><br></td>
           <td><a href="link to game2 when the image is clicked" alt="Game2" target="blank" onclick="AfficherCacher('Image2')"> <img src="the image clicked to open Game2+Image2.jpg" width="1689" height="955" class="img-fluid atto_image_button_text-bottom"></a><br></td>
        </tr>
    </tbody>
</table>

then

</table>
   <table style="whatever">
    <tbody>
        <tr style="whatever">
            <td>
                <div id="Image1">
                    <ul>
                        <img src="Image1.jpg">
                    </ul>
                </div>
            </td>
</table>
   <table style="whatever">
    <tbody>
        <tr style="whatever">
            <td>
                <div id="Image2">
                    <ul>
                        <img src="Image2.jpg">
                    </ul>
                </div>
            </td>

And then the JavaScript part at the end making it all work:

<p>
    <script type="text/javascript">
        // <![CDATA[
        function AfficherCacher(texte) {
            var test = document.getElementById(texte).style.display;
            if (test == "block") {
                document.getElementById(texte).style.display = "none";
            } else {
                document.getElementById(texte).style.display = "block";
            }
        }
        // ]]>
    </script>
</p>

The only thing is that both Image1 and Image2 can be displayed on the page at the same time, which i DO NOT want. I would like for opening Image2 to make Image1 disapear, and for opening Image1 to make Image2 disapear.

I do not know what to use for this.

Thank you in advance for your help.

I have tried inventing “if” conditions, but I am not JavaScript (or CSS) litterate, so I’m going in blind and I’m clearly doing something wrong. I don’t know what I’m able to use and what exists/works.

React Component Executes Sync Operation Twice Despite Guards Against Duplicates

I’m encountering a challenging issue where my React component, designed to sync data with a backend, executes its sync operation twice in quick succession. This happens even though I’ve implemented several measures to prevent such duplicates.

Context:

Framework/Library Versions: React with Dexie for IndexedDB and axios for HTTP requests.
Component Goal: The SyncWorker component aims to synchronize unsynced items from IndexedDB to a backend server upon detecting an online status.
Duplicate Operation Issue: Despite measures to prevent duplicate operations, the sync action is executed twice, roughly a second apart, confirmed by backend logs and client-side observations.

Detailed Component Implementation:

import { useCallback, useEffect, useRef, useState } from "react";
import { useLiveQuery } from "dexie-react-hooks";
import axios from "axios";
import { DeviceConfiguration, db } from "../../db"; // IndexedDB setup
import uploadFile from "../helpers/uploadFile"; // Handles file uploads
import useFirebase from "../hooks/useFirebase"; // Custom hook for Firebase storage
import { base64ToFile } from "../helpers/base64ToFile"; // Utility for file conversions

function SyncWorker() {
  const queryResults = useLiveQuery(() => db.configurations.toArray(), []);
  const { storage } = useFirebase();
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  const processingIdsRef = useRef<Set<number>>(new Set());

  const syncItems = useCallback(async (unsynced: DeviceConfiguration[]) => {
    for (const item of unsynced) {
      if (processingIdsRef.current.has(item.id!)) continue;
      processingIdsRef.current.add(item.id!);
      console.log("Processing id: ", item.id);

      const imageAsFile = base64ToFile(item.photo, `${item.position_identifier}_${item.serial_number}_${new Date().toISOString()}`);

      try {
        const imageUrl = await uploadFile(storage!, imageAsFile, `jobs/${item.ongoing_job_id}/${item.position_identifier}`, imageAsFile.name);
        
        await axios.patch(`${process.env.REACT_APP_BACKEND_URL}/ongoing-jobs/configure-device`, {
          ongoing_job_id: item.ongoing_job_id,
          type: item.type,
          image_url: imageUrl,
          position_identifier: item.position_identifier,
          serial_number: item.serial_number,
        });

        await db.configurations.update(item.id!, { synced: true });
        processingIdsRef.current.delete(item.id!);
      } catch (err) {
        processingIdsRef.current.delete(item.id!);
        console.error("Error syncing item: ", err);
      }
    }
  }, [storage]);

  useEffect(() => {
    if (!queryResults || !isOnline) return;
    const unsynced = queryResults.filter(item => !item.synced);
    if (unsynced.length === 0) return;
    console.log("Starting sync for", unsynced.length, "items");
    syncItems(unsynced);
  }, [queryResults, isOnline, syncItems]);

  return null;
}

export default SyncWorker;

Observations and Debugging Attempts:

  • Server-Side Logs: Upon placing a log at the beginning of my route handler on the server, it prints twice for a single sync operation initiation from the client, indicating the server receives two requests.
  • Client-Side Logs: The log in my React component (console.log(“Starting sync for”, unsynced.length, “items”)) prints once in the browser’s console. However, using Console Ninja (a tool that shows logs inline in VS Code), the same log appears twice, albeit spaced closely together (about a second apart).
  • Measures Taken: I’ve confirmed that React Strict Mode is disabled to rule out its effect of doubling lifecycle methods for debugging purposes. Additionally, I’ve used a Set to track processing items by ID, aiming to prevent re-processing of items already in sync.

Questions:

  • What could be causing the duplicate execution of the sync operation, especially given the preventive measures in place?
  • How can I further diagnose or debug this issue, considering the discrepancies between different logging methods?
  • Is there any aspect of the useEffect or useCallback hooks, or perhaps the way state is managed and updated, that could inadvertently trigger duplicate operations?

Cant convert “application/x-www-form-urlencoded” to “application/json” JavaScript Flask

I’m trying to pull image from client(javascript) to sever(flask) but i got error while doing that. Even i tried to set ‘Content-Type’: ‘application/json’ but when i return the ‘content_type’ it gave me ‘application/x-www-form-urlencoded’. Please help me.

This is my app.py


    @app.route('/')
    @app.route('/index')
    def index():
        return render_template('index.html')

    @app.route('/save-image', methods=['POST'])
    def save_image():

        content_type = request.headers.get('Content-Type')
        if (content_type != 'application/json'):
            return content_type
        # This return application/x-www-form-urlencoded

        data = request.get_json()
        if not data or not data.get('imageData'):
            return 'Missing image data'

        image_data = data['imageData']

        image_data = image_data.split(',')[1]
        image_data = base64.b64decode(image_data)
        filename = f'{uuid.uuid4()}.png'
        filepath = os.path.join('images', filename)

This is my JavaScript

<button id="snap">Take Photo</button>
<form method="POST" action="/save-image">
  <video id="video" width="600" height="440" autoplay style="background-color: grey"></video>
  <canvas name="image" id="canvas" width="600" height="440" style="background-color: grey"></canvas>
  <button onclick="sendCanvasImage()">Convert to Image</button>
</form>

<script>
// Elements for taking the snapshot
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices.getUserMedia({ video: true })
    .then(function(stream) {
      video.srcObject = stream;
      video.play();
    });
}

document.getElementById("snap").addEventListener("click", function() {
  context.drawImage(video, 0, 0, 600, 400);
});

async function sendCanvasImage() {
  var canvas = document.getElementById('canvas');
  var imageData = canvas.toDataURL('image/png'); // Specify image format (optional)

  var response = await fetch('/save-image', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json' // Set content type
    },
    body: JSON.stringify({ imageData }) // Send data in JSON format
  });
}
</script>

Twitch message filter from spammers

I’m moderating twitch chat using bot on node.js.
We have a problem, sometimes bots are raiding our channel and spam messages like:

  • 88|неodeтыe голышкuнсы в т_еле_ж̴eч_кe dosia739
  • гolышkи шkoднuчku в-телеграмчике : juice644 |82
  • 87|rолышкu wkоlьницы в теlеграм4икe / recrenт361
  • 89|спуctuл cпeрму на tрусы шкодниц – тeлеrрам aunkerе450
  • 62 oтсосала охрaнниkу, чтобы tот пустил 6ез смeнки, чеkай синегрaм : buster824
  • 88 пaрни 13 leт дрочаt dруг дpугу при пoдруге в тгшноu recrеnt361
  • 84 clиb wkolьниц в телеrе -> juice644
  • JN шkодницы 6aлyются b тyалете wколы в t.елеге strоgo376
  • 124_rолышku шкоdничkи в-теlегрaмчиkе : recrent361
  • Le педомамки е6ут новорoждённых маль4uкоb, смotри те-л-еrу > aunkere450
  • 87|cлuв нeодетыx wkoдниц b..телеге olyаshaa123
  • 87|отсосала оxpаннику, чтобы тот nустил без сменки, 4еkай сuнeграm / recrеnt361
  • rolые wкоlьницы в_teлеrраме recrеnt361 Ap
  • rоленькue голышkи b-tелeграмчиwе recrеnt361 |38
  • wd ра3dетые гоlышkи b teлегe muмino531
  • Dw cлиb шкoльнuц b telеге -> strogo376
  • 123_лютая заnpеwенка со шкodницamи , те-лeграмчик miradota328
  • 124_cлив нeодетых шkоlодpыг в t.е.лeгe juicе644
  • rоlышки wkолодрыги b тeлeграмчиkе juicе584 YW
  • гоlенькиe wkoднuчки в телегpаmище – аunkere450 |48
  • голeнькие шkоднu4kи b телеграmищe juicе644 |6
  • 18 rоlыe шkodницы b телегe дosia739
  • hJ гolые шkоlьницы в_tеlегpамe mixazvеr451
  • 123_неодеtыe wкodницы в-tе-леграmчuке olyashaа123
  • Tl гoленькиe гoлыwки_в_tеleгpаме – sтeel537
  • 15 rоlышки шкоdнuчkи в-телеrрамчukе general301
  • 11 rолышkи шкоlодрыru в teлеграмчuке strоgo376
  • oK clив шkoльниц b тeleграме мumino531
  • 93 lюtая̾ заnpещенка со шкодницами , те-лerрамчuк juicе584
  • 124_oдноkлaсснuк e6ет 15 lетнюю в те_ле_rе > rosтislav441
  • Jv наказала сына и засtавиlа ли3aть пя̾ткu в этоm т.r. tx740

And I have lack of understanding what is similar and how to differ sthis messages from normal chat users

The way I do it right now is adding every last letter and numbers to check if it contains in message, but I dont think it’s reliable for future and works only after spam is occur

if (
    text.toLowerCase().includes('a739') ||
    text.toLowerCase().includes("e644") ||
    text.toLowerCase().includes("e450")
    //etc.
  ) {
    await apiClient.asUser(
      nyaka,
      async (ctx) =>
        await ctx.moderation.banUser(msg.channelId, {
          reason: `${user}: ${text}`,
          user: msg.userInfo.userId,
        })
    );

Type for custom lazy Promise.all

I have a LazyPromise object with all method. It works like Promise.all but the promises start the call not on initialization, eg.:

// It started executing as soon as it was declared
const p1 = Promise.all([Promise.resolve(1), Promise.resolve('foo')])

// It started executing only when `p2.then()` is called
const p2 = LazyPromise.all([() => Promise.resolve(1), () => Promise.resolve('foo')])

this is the implementation

class LazyPromise {
  static all(lazies: Array<() => Promise<any>>){
    return Promise.all(lazies.map(lazy => lazy()));
  }
}

usage

const result = LazyPromise.all([() => Promise.resolve(1), () => Promise.resolve('foo')]).then(result => console.log(result))

I want make the result with correct types.
Now result is a any[] I want: [number, string]

How infer the correct result types?

Is it possible to play a sound into the microphone at any given time after the websites code already called getUserMedia function?

Is it possible to play a sound into the mic at any given time after the websites code already called the getMediaDevices function?
I am using javascript and puppeteer.

With Flimm’s answer (Possible to Get Puppeteer Audio Feed and/or Input Audio Directly to Puppeteer?) I can play the sound only once, at the start, where the websites code calls the getMediaDevices function.

Evaluation failed: a when sending media

I am trying to build a whatsapp bot using electron and whatsapp-web.js. The bot works fine with sending normal messsages like text, but when I try to pass an image it throws this error:

Server stdout: Error: Evaluation failed: a
    at ExecutionContext._ExecutionContext_evaluate (D:ProjectsWebProjectsWhatsapp Sendernode_modulespuppeteer-corelibcjspuppeteercommonExecutionContext.js:229:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async ExecutionContext.evaluate (D:ProjectsWebProjectsWhatsapp Sendernode_modulespuppeteer-corelibcjspuppeteercommonExecutionContext.js:107:16)
    at async Client.sendMessage (D:ProjectsWebProjectsWhatsapp Sendernode_moduleswhatsapp-web.jssrcClient.js:938:28)
    at async D:ProjectsWebProjectsWhatsapp Senderserverscript.js:167:17

my code:

var media = MessageMedia.fromFilePath(image_path);
console.log(media);
await client.sendMessage(groups[0]._serialized, media, {
    caption: message,
});

I debugged my code and there was nothing. the way I send images is by letting the user select an image and convert it to base64 in the html. when he clicks send, the base64 is re-converted back into an image in a local path like project/data/image.jpg and then that path is used in the MessageMedia.fromFilePath method. I ensured the image is saved and the path is correct. also the groups[0] returns the first common group between this number and the authenticated number and it works just fine. can someone help me?

EDIT:

I found that this way didn’t pass the data parameter in the MessageMedia object, so I tried to create it manually like new MessageMedia('image/png', image //base64, fileName) and now it shows this error

Server stdout: Error: Evaluation failed: DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
    at window.WWebJS.mediaInfoToFile (pptr://__puppeteer_evaluation_script__:520:35)
    at window.WWebJS.processMediaData (pptr://__puppeteer_evaluation_script__:317:36)
    at window.WWebJS.sendMessage (pptr://__puppeteer_evaluation_script__:19:39)
    at pptr://__puppeteer_evaluation_script__:10:45
    at ExecutionContext._ExecutionContext_evaluate (D:ProjectsWebProjectsWhatsapp Sendernode_modulespuppeteer-corelibcjspuppeteercommonExecutionContext.js:229:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async ExecutionContext.evaluate (D:ProjectsWebProjectsWhatsapp Sendernode_modulespuppeteer-corelibcjspuppeteercommonExecutionContext.js:107:16)
    at async Client.sendMessage (D:ProjectsWebProjectsWhatsapp Sendernode_moduleswhatsapp-web.jssrcClient.js:938:28)
    at async D:ProjectsWebProjectsWhatsapp Senderserverscript.js:167:17