Smart search box api in node js

i want to create end point controller function in node js and make auto complite in resulte, i use MongoDB.

this is my function

 exports.searchLectures = asyncHandler( async (req, res) => {
  const search = req.query.search;
  try {
   
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message
    });
  }

});

and this is my model

const mongoose = require('mongoose');

const lectureSchema = new mongoose.Schema({
    teacher: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    student: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: false },
    maxStudents: { type: Number, required: false, default: 1 },
    price: { type: Number, required: true },
    appointment: { type: Date, required: true },
    period: { type: Number, required: true },  // in minutes
    course: { type: String, required: true },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'CourseCategory', required: true },
    courseType: { type: String, required: true, enum: ['university', 'school'] },
    title: { type: String, required: true },
    description: { type: String, required: true },
    status: { type: String, required: false, default: 'available', enum: ['available', 'done', 'reserved', 'canceled'] },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment', required: false }],
    rate: { type: Number, required: false },
    rateCount: { type: Number, required: false },
}, { timestamps: true });

const Lecture = mongoose.model('Lecture', lectureSchema);
module.exports = Lecture;

i want to search by title , course , teacher.name and category.name and alway the function return title

Keep scroll positions on page by url

Can you fix the script, which keeps position on difrent pages with no problem, until there you have some pages with redirected to same php file, but different URL (thanks RewriteRule)?
Would like to keep position even with atributes in URL. For example – page1.php is same as page1.php&abc=1 but diferent of page2.php. This script takes all these pages as same URL so it keeps same position, even if you did not visited second page yet.

.htaccess

RewriteRule page1.php detail.php
RewriteRule page2.php detail.php
RewriteRule page3.php detail.php

script:

<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var scrollpos = localStorage.getItem("scrollpos");
        if (scrollpos) window.scrollTo(0, scrollpos);
    });

    window.onscroll = function (e) {
        localStorage.setItem("scrollpos", window.scrollY);
    };
</script>

new File() has bigger size than origin blob

I have jQuery ajax request for file and it is returned OK with some size.
Ajax request is with param: xhrFields.responseType = 'blob';
When I process ajax response than response size is the same with response origin filesize.
Response size is 3004260. File size physicaly has 3177066 and its jpg file.

But when I use this:

var file = new File([response], filename, {type: 'application/force-download'});

file.size is 5754539.
than file.size is bigger that origin response. I will save it by:

var url = URL.createObjectURL(file);
console.log(url);
// create a hidden anchor element to download the blob as a file.
var anchorElem = document.createElement("a");
anchorElem.style.display = "none";
anchorElem.href = url;
anchorElem.download = 'test.jpg';
// append the anchor element on to the document body.
$("body").append(anchorElem);
// trigger a click event on this anchor element.
anchorElem.click();
// clean-up
URL.revokeObjectURL(url);

and file is saved but broken because it impossible open it. File have double filesize.
why? What is wrong?

PHP which will send file is:

header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="test.jpg"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: 3177066');
echo $filecontent;

Origin and good file looks like:
enter image description here

Wrong file looks like this:
enter image description here

How come visiting child component loses functionality?

I have an app that has a 3 JSX files:
1-one for controlling states
2-one for creating items
3-one for viewing created items as a table.

Here is a code sandbox: https://codesandbox.io/p/sandbox/flamboyant-roman-forked-8hw8x2

When viewing the controlling files component(1), the functionality of adding items and viewing the table works. When I go directly to the pages for creating items / viewing the table the functionality does not. Why is this?

Thanks for views

Javascript new File() has bigger size than origin blob

I have jQuery ajax request for file and it is returned OK with some size.
Ajax request is with param: xhrFields.responseType = 'blob';
When I process ajax response than response size is the same with response origin filesize.

But when I use this:

var file = new File([response], filename, {type: 'application/force-download'});

than file.size is 2x bigger that origin response. I will save it by:

var url = URL.createObjectURL(file);
console.log(url);
// create a hidden anchor element to download the blob as a file.
var anchorElem = document.createElement("a");
anchorElem.style.display = "none";
anchorElem.href = url;
anchorElem.download = 'test.jpg';
// append the anchor element on to the document body.
$("body").append(anchorElem);
// trigger a click event on this anchor element.
anchorElem.click();
// clean-up
URL.revokeObjectURL(url);

and file is saved but broken because it impossible open it. File have double filesize.
why? What is wrong?

Navbar link color not remaining at green when clicked

I have a simple navbar that I am trying to get the color to be green when clicked. However it does not seem to be working.

When I hover over the link it turns green and works fine. However I cannot get it so that when I click on the link it remains green and if I click another link the new active turns green and the previous active turn white.

Here’s the HTML and CSS code I have come up:

<nav>
    <ul>
       <li><a class="nav-link" href="index.html"><i class="fa-solid fa-house"></i></a></li>
        <li><a class="nav-link" href="skills.html"><i class="fa-solid fa-tools"></i></a></li>
         <li><a class="nav-link" href="project.html"><i class="fa-solid fa-laptop-code"></i></a></li>
         <li><a class="nav-link" href="contact.html"><i class="fa-solid fa-paper-plane"></i></a></li>
     </ul>
</nav>
nav {
    display: flex;
    justify-content: center;
}

nav ul {
    display: flex;
    list-style: none;
    gap: 30px;
}

.nav-link {
    color: white;
    text-decoration: none;
    font-size: 16px;
    transition: 0.3s;
}

.nav-link:hover {
    color: #32CD32;
}

.nav-link.active {
    color: #32CD32;
}

Unable to set breakpoint in VSCode debugging Chrome (client side JS)

I’m struggling with how to define the correct launch.json configuration to enable client side JS debugging in VSCode.

The setup is:

  • I am using webpack to create a single JS file, with sourcemaps
  • I am able to debug in Chrome Devtools, and the sourcemaps load correctly
  • My workspace looks like this:
${workspaceFolder}/client/src <== Source js files (in various subfolders)
${workspaceFolder}/client/web <== Web root
${workspaceFolder}/client/web/js/core <== Location of webpack output JS (and source map)

I have a launch.json config that looks like this:

{
  "type": "chrome",
  "name": "http://localhost:8080/",
  "request": "launch",
  "url": "http://localhost:8080/",
  "webRoot": "${workspaceFolder}/client/",
  "sourceMaps": true
}

I am unable to set a breakpoint, and the “troubleshooter” in VSCode tells me this:

✅ This breakpoint was initially set in:

/<workspaceFolder>/client/src/ui/hello.js line 123 column 1

❓ We couldn't find a corresponding source location, but found some other files with the same name:

 - /<workspaceFolder>/client/src/ui/hello.js

You may need to adjust the webRoot in your launch.json if you're building from a subfolder, or tweak your sourceMapPathOverrides.

I am not sure how I am supposed to interpret this. The file path that this troubleshooter is saying contains the breakpoint (/client/src/ui/hello.js) is the same as the path it says it found a file with the same name.

I have tried various values for webRoot (e.g. ${workspaceFolder}/client/web, ${workspaceFolder}/client/web/js etc), none work, and I’m just not sure what it’s asking me for.

Anyone else have an idea on what the launch config needs to look like?

Is there a way to use a function which references an object that in turn references that function?

I’m working on a practice game that uses an array of objects (plants) that will be chosen randomly. Questions are asked about light and water requirements, winning or losing the plant and moving onto the next based on user answers.

My problem is that I can’t use a function that hasn’t been initialized, but I can’t initialize the function without initializing the plant objects containing the functions first.

I tried putting the plants array inside the newPlant function and use “this” to reference the function within the plant objects but came up with undefined errors. Any help is appreciated!

Repo link: https://github.com/ChristinaBohn/botany-game

Code in js file so far:

let xp = 0;
let coins = 30;
let plantHealth = 100;
let collection = [];

// Player controls
const button1 = document.querySelector('#button1');
const button2 = document.querySelector('#button2');
const button3 = document.querySelector('#button3');

// Plant controls
const button4 = document.querySelector('#button4');
const button5 = document.querySelector('#button5');

// Text
const text = document.querySelector('#text');
const xpText = document.querySelector('#xpText');
const coinText = document.querySelector('#coinText');

// Plant collection
const plantTiles = document.querySelector('#plantTiles');
const plantName = document.querySelector('#plantName');
const healthText = document.querySelector('#healthText');

const plants = [
    {
        id: 0,
        name: "Snake Plant (easy care)",
        light: {
            "button text": ["Place plant in low light", "Place plant in medium light", "Place plant in bright light"],
            "button functions": [newPlant.askLight, newPlant.askLight, newPlant.askLight],
            text: "You have received a Snake Plant (easy care)! Where on your plant shelf will you place your plant?"
        },
        water: {
            "button text": ["Don't water at all", "Water a little", "Water a lot"],
            "button functions": [addPlant, addPlant, addPlant],
            text: "Good job! Snake plants are happy in any light. How much water do you want to give your plant?"
        },
        clippingCost: 5
    },
    {
        id: 1,
        name: "Hoya (medium care)",
        light: {
            "button text": ["Place plant in low light", "Place plant in medium light", "Place plant in bright light"],
            "button functions": [losePlant, newPlant.askWater, newPlant.askWater],
            text: "You have received a Hoya (medium care)! Where on your plant shelf will you place your plant?"
        },
        water: {
            "button text": ["Don't water at all", "Water a little", "Water a lot"],
            "button functions": [losePlant, addPlant, losePlant],
            text: "Good job! Hoyas are happy in medium to bright light. How much water do you want to give your plant?"
        },
        clippingCost: 10
    },
    {
        id: 2,
        name: "Calathea (difficult care)",
        light: {
            "button text": ["Place plant in low light", "Place plant in medium light", "Place plant in bright light"],
            "button functions": [losePlant, newPlant.askWater, losePlant],
            text: "You have received a Clathea (difficult care)! Where on your plant shelf will you place your plant?"
        },
        water: {
            "button text": ["Don't water at all", "Water a little", "Water a lot"],
            "button functions": [losePlant, addPlant, losePlant],
            text: "Good job! Calatheas are happy in medium light only. How much water do you want to give your plant?"
        },
        clippingCost: 15
    }
];

let plantShop = [...plants];

const locations = [
    {
        name: "welcome",
        "button text": ["Begin!", "Begin!", "Begin!"],
        "button functions": [newPlant.askLight, newPlant.askLight, newPlant.askLight],
        text: "Welcome to Botany Bliss. Take care of each new plant based on your plant knowledge and watch your plant collection grow!"
    },
    {
        name: "lose plant",
        "button text": ["Try again", "Try again", "Try again"],
        "button functions": [newPlant.askLight, newPlant.askLight, newPlant.askLight],
        text: "Oh no, your new plant didn't like that! You've lost this plant. Try again?"
    },
    {
        name: "lose game",
        "button text": ["Start over?", "Start over?", "Start over?"],
        "button functions": [welcome, welcome, welcome],
        text: "Oh no, your new plant didn't like that and you have no remaining plants in your collection! Game over. Would you like to play again?"
    },
    {
        name: "win game",
        "button text": ["Start over?", "Start over?", "Start over?"],
        "button functions": [welcome, welcome, welcome],
        text: "Congratulations, you have every available plant in your home collection! Would you like to play again?"
    }
];

// Use same random plant for one iteration each of askLight and askWater
function useRandomIndex() {
    let plantIndex = Math.floor(Math.random() * 3);
    let currentPlant = plants[plantIndex];
        
    function askLight() {
        button1.innerText = currentPlant["light"]["button text"][0];
        button2.innerText = currentPlant["light"]["button text"][1];
        button3.innerText = currentPlant["light"]["button text"][2];
        button1.onclick = currentPlant["light"]["button functions"][0];
        button2.onclick = currentPlant["light"]["button functions"][1];
        button3.onclick = currentPlant["light"]["button functions"][2];
        text.innerHTML = currentPlant.light.text;
    };

    function askWater() {
        button1.innerText = currentPlant["water"]["button text"][0];
        button2.innerText = currentPlant["water"]["button text"][1];
        button3.innerText = currentPlant["water"]["button text"][2];
        button1.onclick = currentPlant["water"]["button functions"][0];
        button2.onclick = currentPlant["water"]["button functions"][1];
        button3.onclick = currentPlant["water"]["button functions"][2];
        text.innerHTML = currentPlant.water.text;
    };

    return { askLight, askWater };
};

const newPlant = useRandomIndex();

// Initialize buttons
button1.onclick = newPlant.askLight;
button2.onclick = newPlant.askLight;
button3.onclick = newPlant.askLight;


function update(location) {
    button1.innerText = location["button text"][0];
    button2.innerText = location["button text"][1];
    button3.innerText = location["button text"][2];
    button1.onclick = location["button functions"][0];
    button2.onclick = location["button functions"][1];
    button3.onclick = location["button functions"][2];
    text.innerHTML = location.text;
}

function welcome() {
    xp = 0;
    coins = 50;
    xpText.innerText = xp;
    coinText.innerText = coins;
    collection = [""];
    plantShop = [...plants];
    update(locations[0]);
    newPlant.askLight();
}

function addPlant() {
    alert("Congratulations! Your plant is happy and thriving. It has been added to your collection.")
    update(locations[2]);
    xp += 5;
    xpText.innerText = xp;
};

function losePlant() {
    update(locations[1])
    xp -= 5;
    xpText.innerText = xp;
};

function loseGame() {
    update(locations[2]);
};

welcome();

Searching Locations in HTML/ Goog Map API

I’m working on a webpage that I’d like to have simulate google map searching. I’m trying to simulate a “pet locations near me” search on google maps, but I’m unsure how googles search works as my attempts have been unsuccessful. Is it possible to simulate a search like this using google map API, or is it too complex, and if possible, how would I go about tackling it? Thank you

CORS Error with Ngrok and Express Server: “No ‘Access-Control-Allow-Origin’ header is present” and 401 Unauthorized

I’m developing a React application that uses Firebase Authentication for Google sign-in. After successful sign-in, I retrieve the Firebase ID token and send it to my Node.js/Express server for verification.

When I attempt to sign in using Google, I encounter the following errors in my browser’s console:

Access to XMLHttpRequest at 'http://localhost:3005/api/verify-token' from origin 'https://e7e7-43-252-15-140.ngrok-free.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


SignUp.jsx:39 Error during sign-in: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

POST http://localhost:3005/api/verify-token net::ERR_FAILED

My React application is running through ngrok at https://e7e7-43-252-15-140.ngrok-free.app, and my Express server is running on http://localhost:3005.

My React application is running through ngrok at https://e7e7-43-252-15-140.ngrok-free.app, and my Express server is running on http://localhost:3005.

What I’ve Tried:

  • I’ve added the cors middleware to my Express server, specifying the ngrok URL as the allowed origin.

  • I’ve verified that the Firebase Admin SDK is correctly initialized on the server.

  • I’ve made sure that the Authorization header is being sent from the react app.

  • I’ve verified the token verification logic on the server side.
    My Question:

Why am I still getting the CORS error and the network error? Is there something wrong with my CORS configuration, or is there another issue that I’m overlooking? How do I properly configure my Express server to allow cross-origin requests from my ngrok URL?

Any help would be greatly appreciated.

Why does this Discord.js command raises an error sometimes?

This is a Discord.js command to send embeds to a specific text channel. I’m struggling a little bit with the replies/updates deferral.

When the modal is submitted, the command raises an Interaction has already been acknowledged. error but just sometimes, and I’m not really sure where I’m doing things wrong.

As far as I know, the .showModal method must be called as a first interaction reply since the modal opening cannot be delayed, and .deferUpdate is used to let the server know that you’re not closing the interaction yet.

/** Controller for the Messages command. */
export default async function (interaction: ChatInputCommandInteraction) {
    try {
        // Modal fields data
        const fields: {
            id: string
            label: string
            style: TextInputStyle
            required: boolean
        }[] = [
            {
                id: 'title',
                label: 'Título',
                style: TextInputStyle.Short,
                required: false,
            },
            { id: 'url', label: 'URL', style: TextInputStyle.Short, required: false },
            {
                id: 'thumbnail',
                label: 'URL de la miniatura',
                style: TextInputStyle.Short,
                required: false,
            },
            {
                id: 'description',
                label: 'Descripción',
                style: TextInputStyle.Paragraph,
                required: true,
            },
            {
                id: 'image',
                label: 'URL de la Imagen',
                style: TextInputStyle.Short,
                required: false,
            },
        ]

        // Modal instance
        const modal = new ModalBuilder({
            customId: 'new-message-modal',
            title: 'Nuevo mensaje',
            components: fields.map(({ id, label, style, required }) =>
                new ActionRowBuilder<TextInputBuilder>().addComponents(
                    new TextInputBuilder()
                        .setCustomId(id)
                        .setLabel(label)
                        .setStyle(style)
                        .setRequired(required),
                ),
            ),
        })

        await interaction.showModal(modal)
        // THIS IS WHERE THE ERROR IS BEING RISEN
        // We wait for the user to press "submit" or "cancel"
        const modalInteraction = await interaction.awaitModalSubmit({
            filter: (i: ModalSubmitInteraction) =>
                i.customId === modal.data.custom_id && i.user.equals(interaction.user),
            time: 60_000,
        })

        await modalInteraction.deferUpdate()

        // Extract values from the modal
        const embedData = {
            title: modalInteraction.fields.getTextInputValue('title') || null,
            url: modalInteraction.fields.getTextInputValue('url') || null,
            description: modalInteraction.fields.getTextInputValue('description'),
            thumbnail: modalInteraction.fields.getTextInputValue('thumbnail') || null,
            image: modalInteraction.fields.getTextInputValue('image') || null,
        }

        // Create a basic embed using only the description (it's mandatory)
        const newMessageEmbed = createEmbed({
            description: embedData.description
        })

        // Dinamically add the fields based on the values provided
        if (embedData.title) newMessageEmbed.setTitle(embedData.title)
        if (embedData.url) newMessageEmbed.setURL(embedData.url)
        if (embedData.thumbnail) newMessageEmbed.setThumbnail(embedData.thumbnail)
        if (embedData.image) newMessageEmbed.setImage(embedData.image)

        // Get the current channel or the provided one
        const selectedChannel = (interaction.options.getChannel('canal') ||
            interaction.channel) as TextChannel

        // Send message to selected channel
        await selectedChannel.send({ embeds: [newMessageEmbed] })

        // Follow up message
        await modalInteraction.followUp({
            embeds: createArrayedEmbed({
                title: 'Asistente de Creación de Mensajes',
                description: '✅ Mensaje enviado correctamente.',
            }),
            flags: 'Ephemeral',
        })
    } catch (error) {
        console.log(error)
    }
}

Salvar/ Gravar informaçoes HTML e JS [closed]

Preciso criar uma tabela dinâmica com informações de estudantes, com funcionalidades de criar, editar e apagar.

Esse projeto é pessoal para facilitar o meu trabalho e dos demais que trabalham comigo.

O problema é que nos computadores da prefeitura não é possível instalar nenhum programa, vou fazer isso usando editor de texto, muito menos um banco de dados ou criar um servidor, o prompt de comando dos computadores é inacessivel.

Existe alguma forma de salvar e atualizar os dados dessa tabela tendo em vista essas restrições?

Javascript regex : how to “update” a matching line using regex?

I have a variable containing a multiline string.
This string is made of markdown formated text.
I want to convert it a “Telegram” compliant markdown format.
To convert titles (identified by lines starting with some “#”) to bold and underlined text I have to use the replace(All) function on the input string.

var t = "### Context AnalysennHere comes the analyse...nnAnd it continues here.nn### And here is another titlenn";
t = t.replace(/#*(.*)nn/g, "__*\$1*__nn");
console.log(t);

I would like, for lines starting with some “#”, to remove the “#”s and to make it start with “__*” and end with “*__”.

With my current expression all the lines are matching.

What am I doing wrong ?

Calling a javascript file from within a javascript function

I am trying to call a javascript file from within a javascript function. I know the file is called (as I can put an alert box in the file and it executes) but I don’t know or can’t work out how to return a value and populate an array;

It will eventually be used with the resume event. If the array is populated do nothing else otherwise invoke the script.

Both files reside locally in the same folder.

$(document).ready(function(){
  function loadScript(file) {
    const newScript = document.createElement('script');
      newScript.setAttribute('src', file);
      newScript.setAttribute('type', 'text/javascript');
      newScript.setAttribute('async', 'true');
                
      newScript.onLoad = function(){
        console.log('${file} loaded successfully.');                 };
      newScript.onLoad = function(){
        console.error('Error loading script: ${file}');
      };
      document.head.appendChild(newScript);
    }
    clubs = loadScript('test.js'); 
  });
});
  
  /* test.js
  team = [];
  for(n=0; n<=3; n++){
    team[n] = {};
    team[n].club = "Team "+n;
  };
  return team;
  */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>