TypeError: booking.populate(…).populate is not a function

I was making a backend application to schedule company visits and when I tried to use Mongoose ‘populate’ function, got this error:

TypeError: booking.execPopulate is not a function

I don’t know what happened but this is my code:

BookingController.js

const Booking = require('../models/Booking')

module.exports = {
  async store(req, res) {
    const { user_id } = req.headers;
    const { spot_id } = req.params;
    const { date } = req.body;

    const booking = await Booking.create({
      user: user_id,
      spot: spot_id,
      date,
    });

    await booking.populate('spot');
    await booking.populate('user');
    await booking.execPopulate();

    return res.json(booking);
  }
}

BookingModel.js

const mongoose = require('mongoose');

const BookingSchema = new mongoose.Schema({
  date: String,
  approved: Boolean,
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  spot: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Spot'
  }
});

module.exports = mongoose.model('Booking', BookingSchema);

Using $_POST to get value ‘input’ inside div?

i would like to get value that i created using js. i did by iterating loop but when i created it i gave it a name inside a div like this

this created by js using createElement

<div id="0" name="classes"> text 
    <input type="text" name="ep0">
        <input type="button" id="remove0" name="remove" value="remove">
</div> 

what i need is to get the value of the input inside div i tried to get it using $_POST in php but i couldn’t. Also i even tried to get all the variables found using var_dump($_POST); but i couldn’t find the div

Submit form to add column in table

I have a table like this:

<table id="criteria-table">
  <thead>
    <tr>
      <th rowspan="2" class="text-center align-middle">#</th>
      <th rowspan="2" class="text-center align-middle">Employee</th>
      <th colspan="3" class="text-center">Order</th>
    </tr>
    <tr>
      <th class="text-center">Priority</th>
      <th class="text-center">Criteria</th>
      <th class="text-center">Unit</th>
    </tr>
  </thead>

  <tbody>
    <tr class="tr_template">
      <td class="text-center">1</td>
      <td class="text-center">Employee A</td>
      <td class="text-center">75%</td>
      <td class="text-center">10</td>
      <td class="text-center">order</td>
    </tr>
  </tbody>
</table>

And I have 2 button in the end of this table:

<a class="btn btn-add-criteria  btn-sm m-btn--icon color" href="javascript:void(0)">
  <i class="la la-plus"></i>ADD CRITERIA
</a>

<a class="btn btn-add-employee  btn-sm m-btn--icon color" href="javascript:void(0)">
  <i class="la la-plus"></i>ADD EMPLOYEE
</a>

When I click add criteria button, a popup will open to type criteria data and submit:

<div class="modal fade" id="popup-add" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
    <div class="modal-content clear-form">
      <!-- Body modal -->
      <div class="modal-body">

        <!-- Form -->
        <form id="frm-add-criteria">
          <div class="row">
            <div class="col-lg-12">
              <div class="m-form__group">
                <div class="criteria-content">

                  <!-- Criteria -->
                  <div class="row modal-row">
                    <div class="col-12">
                      <label class="font-weight-bold">Criteria</label>
                      <div class="input-group">
                        <select name="kpi_criteria_id" id="kpi_criteria_id" class="form-control">
                          <option value="1">Order</option>
                          <option value="2">Contract</option>
                          <option value="3">Revenue</option>
                        </select>
                      </div>
                    </div>
                  </div>

                  <!-- Priority -->
                  <div class="row modal-row">
                    <div class="col-12">
                      <label class="font-weight-bold">Priority</label>
                      <div class="input-group">
                        <input type="text" class="form-control" id="priority" name="priority" placeholder="Input criteria" aria-describedby="basic-addon2">
                      </div>
                    </div>
                  </div>

                  <!-- Amount -->
                  <div class="row modal-row">
                    <div class="col-12">
                      <label class="font-weight-bold">Amount</label>
                      <div class="input-group">
                        <input type="text" class="form-control" id="kpi_value" name="kpi_value" placeholder="Input amount" aria-describedby="basic-addon2">
                      </div>
                    </div>
                  </div>

                </div>
              </div>
            </div>
          </div>

          <!-- Footer modal -->
          <div class="modal-footer">
            <div class="m-portlet__foot m-portlet__no-border m-portlet__foot--fit ss--width--100">
              <div class="m-form__actions m--align-right">
                <button data-dismiss="modal" class="btn btn-metal bold-huy m-btn m-btn--icon m-btn--wide m-btn--md">
                  <span class="ss--text-btn-mobi">
                    <i class="la la-arrow-left"></i>
                    <span>CANCEL</span>
                  </span>
                </button>

                <button type="submit" onclick="" id="btn-save-criteria" class="btn btn-success color_button son-mb  m-btn m-btn--icon m-btn--wide m-btn--md btn_add_close m--margin-left-10">
                  <span class="ss--text-btn-mobi">
                    <i class="la la-check"></i>
                    <span>SAVE</span>
                  </span>
                </button>
              </div>
            </div>
          </div>

        </form>

      </div>
    </div>
  </div>
</div>

After I submit the form in modal, it will add one more column like this for all employee row in table:

enter image description here

Here is my old table:

enter image description here

After submit form modal:

enter image description here

Same like this, when I click add employee, it will show a modal for me to choose employee, then it will insert one more employee row to this table with all criteria I add before.

Here is my JSFiddle to show you what I did.

I really don’t know how to do this so forgive me if you feel I just give you about code not solution.

Hope you can give me a good advise to handle this.

Thank you very much!

This function will not work, the console says the function is undefined. Using For…of loop with object

This function is supposed to accept a number, corresponding to a key and return the value for that key. I chose a for…of loop because I wanted to be able to iterate through the object. Here’s the code:

function printDay(num) {
    const days = {
        '1': Sunday,
        '2': Monday, 
        '3': Tuesday,
        '4': Wednesday, 
        '5': Thursday,
        '6': Friday,
        '7': Saturday
    };
    for (let day of Object.keys(days)) {
        return (days[day]);
    }    
}

How do I export a redux reducer that uses a prepare function

I am currently working on a anecdotes application, and anytime a user votes on a certain anecdote, it should display a notification then disappear 10 seconds later, however, I am struggling to export my reducer that uses the prepare function that is suppose to, I think, get my multiple arguments ready for the actual reducer. Here is my code in question:

import { createSlice } from "@reduxjs/toolkit";

const notificationSlice = createSlice({
  name: 'notification',
  initialState: '',
  reducers: {
    test: {
      createNotification(state, action) {
        console.log(action)
      },
      prepare(...args) {
        return {
          payload: args
        }
      }
    }
}})

export const { createNotification } = notificationSlice.actions
export default notificationSlice.reducer

I thought I could just export const { test.createNotification } = notificationSlice.actions but that does not work due to the dot in the variable name.

How would I then export my createNotification reducer since test is the first property of the reducers object?

I am trying to scrape xml data using cheerio

From the Axios response data saved from the .xml site to XML object, I want to pass the data from XML to cheerio to find and select first name, last name, party, state, and vote_cast for each element on the XML page.

I want the object saved as its list name and pushed into the senator array.

Thank You

const PORT = 8000
const express = require('express')
const axios = require('axios')
const cheerio = require('cheerio')

const app = express()

const senator = []

app.get('/', (req, res) => {
    res.json('Donkey, Dino, Elephant, and Rino API')
})

app.get('/votes', (req, res) => {

    axios.get('https://www.senate.gov/legislative/LIS/roll_call_votes/vote1172/vote_117_2_00255.xml')
        .then((response ) => {
            const xml = response.data
            const $ = cheerio.load(xml)

            $('member:contains("last_name")',xml).each(function () {
                const name = $(this).text()
                senator.push({
                    name
                })
            })
            res.json(senetor)
        }).catch((err) => console.log(err))
})

app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))

Some one knows how to do a square colids with other square?

Some one knows how to do a square colids/don’t pass through with other square ? or has an video or article, i’ve tried to get the border position
of squares but it didn’t seems to be efficient, because depending the side i gonna touch the other, it’ll needs too much ifs. aosgbasiobgoiabsoibdoisboibgioasoiiogboaisbkjgbakbgoaibsoigbaoibgoisbgoiabsogiabsiojgbfiugajhbgaguibsbguuibgoaisgboigbaiosbgoibabgosbgoiabiogboibobgoegouigqgpopnjbvosidugurpqpvpdvpeihgvv

        const player = document.querySelector(".player");
        const getProp = (val) =>
          parseInt(getComputedStyle(player).getPropertyValue(val));

        //when inrease +40 it goes down, and if decrease -40 it goes up
        const go_Up_And_Down = (val) => {
          player.style.top = `${getProp("top") + (val > 0 ? 40 : -40)}px`;
        };

        //when inrease +40 it goes Right, and if decrease -40 it goes left
        const go_Right_And_Left = (val) => {
          player.style.left = `${getProp("left") + (val > 0 ? 40 : -40)}px`;
        };
<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="style.css">
            <title>Document</title>
        </head>
        <body>

        <div class="testes"></div>
            <div class="player">
            </div>

            <div class="boxOnMap" name="Primeiro" style="position:absolute; top: 140px;left: 1000px;"></div>
            

            <div class="controls"> 
                <p id="warning">touched Some Square</p>
                <div class="butnControls" >
                    <button id="up" onclick="go_Up_And_Down(0)">/</button>
                <button id="left" onclick="go_Right_And_Left(0)">(-</button>
                <button id="right" onclick="go_Right_And_Left(1)" >-)</button>
                <button id="down" onclick="go_Up_And_Down(1)">/</button>
                <button id="me" onclick="where_im()">me</button>
                </div>
            </div>


            <script src="./main.js" ></script>
            
        </body>
        </html>
const player = document.querySelector(".player");
        const getProp = (val) =>
          parseInt(getComputedStyle(player).getPropertyValue(val));

        //when inrease +40 it goes down, and if decrease -40 it goes up
        const go_Up_And_Down = (val) => {
          player.style.top = `${getProp("top") + (val > 0 ? 40 : -40)}px`;
        };

        //when inrease +40 it goes Right, and if decrease -40 it goes left
        const go_Right_And_Left = (val) => {
          player.style.left = `${getProp("left") + (val > 0 ? 40 : -40)}px`;
        };
<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="style.css">
            <title>Document</title>
        </head>
        <body>

        <div class="testes"></div>
            <div class="player">
            </div>

            <div class="boxOnMap" name="Primeiro" style="position:absolute; top: 140px;left: 1000px;"></div>
            <div class="boxOnMap" name="Segundo" style="position:absolute; top: 360px; left: 640px;"></div>

            <div class="controls"> 
                <p id="warning">touched Some Square</p>
                <div class="butnControls" >
                    <button id="up" onclick="go_Up_And_Down(0)">/</button>
                <button id="left" onclick="go_Right_And_Left(0)">(-</button>
                <button id="right" onclick="go_Right_And_Left(1)" >-)</button>
                <button id="down" onclick="go_Up_And_Down(1)">/</button>
                <button id="me" onclick="where_im()">me</button>
                </div>
            </div>


            <script src="./main.js" ></script>
            
        </body>
        </html>

Shopify JSON Api

I am building a collection in shopify and I am also using vue. What I did initially was I converted the liquid collection object to a javascript object like this:

const collection = (() => {
  const collection = {{ collection | json }}
  const products = {{ collection.products | json }}
  collection.products = products
  return collection
})();

Once I did this I added some extra logic to try to create linked products based on title. So if there’s a bunch of products in a collection, the ones that have the same title will be linked. I got this working well with this bit of code:

collection.products.forEach(product => {
    product.linked_products = 
      collection.products
        .filter(linked_product => linked_product.id !== product.id && linked_product.title === product.title)
  })

Now here’s the thing, shopify is server side rendered so when a filter is clicked, it’s an href and it updates the url and reloads the page. I thought I could just use the same url but use it with fetch. Long story short this does not work and theres some reasons why it doesn’t work.

In shopify you can create a template with json in it and actually fetch it. So I created a template with a {% layout none %} tag and started building the json.

The below does work. If the template is collection.foo.liquid it can be fetched with

fetch('https://example.com/collections/someCollection?view=foo')

So my question is the above vanilla javascript where I create the linked_products property on the object, how can I do this in this scenario with liquid and json. I got everything to work up to this point and the linked_products part is not working. I am really confused with this because it seems like it should work fine but nothing happens.

{% layout none %}

{
  "title": {{ collection.title | json }},
  "description": {{ collection.description | json }},
  "products": [
    {% for product in collection.products %}
      {
        "title": {{ product.title | json }},
        "variants": [
          {% for variant in product.variants %}
            {
              "id": {{ variant.id }}
            }{% unless forloop.last %},{% endunless %}
          {% endfor %}
        ],
        "linked_products": [
          {% for linked_product in collection.products %}
            {% if linked_product.id != product.id and linked_product.title == product.title %}
              {
                "title": {{ linked_product.title | json }}
              }{% unless forloop.last %},{% endunless %}
            {% endif %}
          {% endfor %}
        ]
      }{% unless forloop.last %},{% endunless%}
    {% endfor%}
  ]
}

if i have this example code:

const collection = [
  title: 'shirts',
  products: [
    { title: 't-shirt', id: 1 },
    { title: 't-shirt', id: 2 },
    { title: 'long-sleeve', id: 3
  ]
]

I am expecting to get an output like this:

const collection = [
  title: 'shirts',
  products: [
    { title: 't-shirt', id: 1, linked_products: [{ title: 't-shirt', id: 2 }] },
    { title: 't-shirt', id: 2, linked_products: [{ title: 't-shirt', id: 1 }] },
    { title: 'long-sleeve', id: 3
  ]
]

Bootstrap Table Load Issues

I’m having challenges with updating my Bootstrap table using the load method. Even when I simplify the problem and try and update using a single record, nothing changes. I would eventually like to update the data set with the rowData, but I want to get the test_data working first.

Index Page

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
  </head>
  <body>
      <div class="mb-3">
          <label for="sequence_input" class="form-label">Sequence Input</label>
          <textarea class="form-control" id="sequence_input" rows="3"></textarea>
      </div>
      <button id="blastButton" type="button" onclick="blast_request();" class="btn btn-primary">Submit Blast Query</button>
      <!-- Modal -->
      <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">FASTA Validation</h5>
              <button type="button" onclick="$('#exampleModal').modal('toggle')" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              There was an error with the FASTA validation. Please check your input and try again. 
            </div>
            <div class="modal-footer">
              <button onclick="$('#exampleModal').modal('toggle')" type="button" class="btn btn-secondary" data-dismiss="modal" data-target="exampleModal">Close</button>
            </div>
          </div>
        </div>
      </div>
      <!-- End Modal -->
      <!-- Start Table -->
      <table
          id="table"
          class="table table-sm"
          >
          <thead>
            <tr>
              <th data-field="id">Hit ID</th>
              <th data-field="def">Hit Definition</th>
              <th data-field="acc">Hit Accession</th>
            </tr>
          </thead>
        </table>
      <!-- End Table -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>
    <script src="./script.js"></script>
  </body>
</html>

My Script

/*
    Function used courtesy of Oxford Protein Informatics Group
    
A javascript function to validate FASTA sequences
*/ function validateFasta(fasta) { if (!fasta) { // check there is something first of all return false; } // immediately remove trailing spaces fasta = fasta.trim(); // split on newlines... var lines = fasta.split('n'); // check for header if (fasta[0] == '>') { // remove one line, starting at the first position lines.splice(0, 1); } // join the array back into a single string without newlines and // trailing or leading spaces fasta = lines.join('').trim(); if (!fasta) { // is it empty whatever we collected ? re-check not efficient return false; } // note that the empty string is caught above // allow for Selenocysteine (U) return /^[ACDEFGHIKLMNPQRSTUVWYs]+$/i.test(fasta); } async function blast_request(){ let form_data = document.getElementById("sequence_input").value let fasta_valid = validateFasta(form_data); if (fasta_valid){ console.log('FASTA data validates') try{ let response = await fetch( 'http://localhost:8000/', { method: 'PUT', headers: {"Content-type": "application/json"}, body: JSON.stringify({"formInput":form_data}) }); // get blast data let blastData = await response.json(); console.log("data received", blastData); // extract relevant fields let rowData = getRowData(blastData) console.log("row data ready", rowData); // load data to table // $('#table').bootstrapTable('load', rowData) test_data = [{id:1, def:"definition1", acc:"acc1"}] $('#table').bootstrapTable('load', test_data) console.log("data loaded to table") } catch (error){ console.log(error) } } else { console.log("Input does not validate"); $('#exampleModal').modal('show') } } function getRowData(input){ n = input['data'].length data = input['data'] console.log(input) rows = [] for (var i = 0; i<n; i++){ rows.push({ id: data[i]['Hit_id'], def: data[i]['Hit_def'], acc: data[i]['Hit_accession'] }) } return rows }

React UseState() Hook [closed]

  • I passed a prop to a child component.
  • The prop send an object to the child component.
  • In the child component I have an array of objects.
  • Then I use the passed prop object and loop through it under a certain condition.
  • When that condition is met then I make some changes to the Array of Objects present in the child component itself.

Now I want to use the useState in a way that when the changes are made to the array of objects in the child prop I want these changes to be added on top of its old version rather then a new array of objects only showing the changes made.

Switching from ReactDOM.render to createRoot makes simple jest test fail

I just started studying “Mastering React Test-Driven Development” by Daniel Irvine, and I figured that it shouldn’t be too hard to convert the examples to React 18. But I am running into trouble converting the very first test in the book using Jest.

The book doesn’t use create-react-app or anything, but instead builds the React apps from scratch, so I’m having trouble finding relevant examples of how to convert the code.

When written as in the book, in React 17 style, the test passes. But if I replace ReactDOM.render() with createRoot(), the test fails.

My application directory looks like:

├── package.json
├── package-lock.json
├── src
│   └── Appointment.js
└── test
    └── Appointment.test.js

and the file contents are:

package.json:

{
  "name": "appointments",
  "version": "1.0.0",
  "description": "Appointments project from Mastering React Test-Driven Development.",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": "example.com"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.18.6",
    "@babel/preset-env": "^7.18.6",
    "@babel/preset-react": "^7.18.6",
    "jest": "^28.1.2",
    "jest-environment-jsdom": "^28.1.3"
  },
  "dependencies": {
    "@babel/runtime": "^7.18.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "jest": {
    "testEnvironment": "jsdom"
  }
}

src/Appointment.js:

import React from 'react';

export const Appointment = () => <div>Ashley</div>;

test/Appointment.test.js:

import React from 'react';
import ReactDOM from 'react-dom';
// import {createRoot} from 'react-dom/client';

import {Appointment} from '../src/Appointment';

describe('Appointment', () => {
  it("renders the customer's first name.", () => {
    const customer = {firstName: 'Ashley'};
    const component = <Appointment customer={customer} />;
    const container = document.createElement('div');
    document.body.appendChild(container);

    ReactDOM.render(component, container);

    // const root = createRoot(container);
    // root.render(component);

    expect(document.body.textContent).toMatch('Ashley');
  });
});

With ReactDOM.render(), the test passes, but I get the following error:

  console.error
    Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot

      11 |     document.body.appendChild(container);
      12 |
    > 13 |     ReactDOM.render(component, container);
         |              ^
      14 |
      15 |     expect(document.body.textContent).toMatch('Ashley');
      16 |   });

      at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
      at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:29670:5)
      at Object.render (test/Appointment.test.js:13:14)

I looked up how to convert ReactDOM.render() to createRoot(), and changed the test to:

import React from 'react';
// import ReactDOM from 'react-dom';
import {createRoot} from 'react-dom/client';

import {Appointment} from '../src/Appointment';

describe('Appointment', () => {
  it("renders the customer's first name.", () => {
    const customer = {firstName: 'Ashley'};
    const component = <Appointment customer={customer} />;
    const container = document.createElement('div');
    document.body.appendChild(container);

    // ReactDOM.render(component, container);

    const root = createRoot(container);
    root.render(component);

    expect(document.body.textContent).toMatch('Ashley');
  });
});

and the test fails as follows:


> [email protected] test
> jest

 FAIL  test/Appointment.test.js
  Appointment
    ✕ renders the customer's first name. (9 ms)

  ● Appointment › renders the customer's first name.

    expect(received).toMatch(expected)

    Expected substring: "Ashley"
    Received string:    ""

      17 |     root.render(component);
      18 |
    > 19 |     expect(document.body.textContent).toMatch('Ashley');
         |                                       ^
      20 |   });
      21 | });
      22 |

      at Object.toMatch (test/Appointment.test.js:19:39)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:317:13)
      at runJest (node_modules/@jest/core/build/runJest.js:407:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:339:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:190:3)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.979 s, estimated 1 s
Ran all test suites.

How can I get this test to pass using createRoot()?

Tailwind custom pseudo element

I’m trying to create a single js file for a component that is used with several styles in my project.
On one page I have several buttons for some features, with a default background color set in the html file (for exemple bg-gray-500).
For buttons where the feature is activated I change the background color, currently with js, but therefore the bg color for the “activated feature” (for exemple bg-blue-500) is defined in the js and this is what I would like to move to the html file.
So, instead of having <button type="button" class="bg-gray-500"></button> and having the js removing the class bg-gray-500 and adding the class bg-blue-500, I wonder if this is possible to have something like <button type="button" class="bg-gray-500 selected:bg-blue-500"></button> where the js would only have to add or remove the class selected to switch between the one and the other color, instead specifing the color itself.
Thank you

How to make JS to show diffrent image

I used that script to show a modal with images, but I want to do that the modal that will pop-up will show the specific image that pressed.
The problem is that the JS is only respond the the first img, but when I add the second img to the script its just wont working… There is any easy way to make the JS work for each img or I need to write and whole script for each img?

HTML:

<div>
   <img src="pics/photos/sample1.png" id="myImg">
   <div id="myModal" class="modal">
      <span class="close">
         &times;
      </span>
      <img class="modal-content" id="img1">
   </div>
</div>
<div>
   <img src="pics/photos/sample2.png" id="myImg">
   <div id="myModal" class="modal">
      <span class="close">
         &times;
      </span>
   <img class="modal-content" id="img2">
</div>
</script src="script.js"><script>

JS:

var modal = document.getElementById("myModal");

var img = document.getElementById("myImg");
var modalImg = document.getElementById("img1"); // second img (img1)
var modalImg = document.getElementById("img2"); // second img (img2)

img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
  modal.style.display = "none";
}

CSS (if there is need to see):

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.9);
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

.modal-content, #caption {
  animation-name: zoom;
  animation-duration: 0.6s;
}

@keyframes zoom {
  from {transform:scale(0)}
  to {transform:scale(1)}
}

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}

Thanks alot!

Search system not working – MongoDB and Next JS

I am trying to make a search system for my Next JS API. This API stores some data like fuel prices and fuel station name, etc. Below is the code:

class ApiFeatures {
  constructor(query, queryStr) {
    this.query = query;
    this.queryStr = queryStr;
  }

  search() {
    const keyword = this.queryStr.keyword
      ? {
          $or: [   //Causing the issue
            {
              name: {
                $regex: this.queryStr.keyword,
                $options: "i",
              },
            },
            {
              email: {
                $regex: this.queryStr.keyword,
                $options: "i",
              },
            },
            {
              //I think this is causing issue. Please read down below for more details.
              petrolPumpName: {
                $regex: this.queryStr.keyword,
                $options: "i",
              },
            },
          ],
        }
      : {};

    this.query = this.query.find({ ...keyword });
    return this;
  }

API function of Next JS.

const handler = catchAsyncErrors(async (req, res) => {
      const apiFeature = new ApiFeatures(
          /// this function is called without searching
          User.find().select("-role -verified"),
          req.query

      // / calling the search function
      ).search();
      const users = await apiFeature.query;
      if (users.length === 0) {
          return res.status(404).json("No User Found");
      }
      return res.status(200).json(users);
});

export default connectToMongo(isAuthenticated(catchAsyncErrors(handler)));

using this function I am trying to fetch data only for the requested query. Example: If the query URL is – http://localhost.com/users?keyword=username then I want list of all the user with that particular user but instead it search for all the user like normal MongoDB find() function does.

**Explaination**
Working of this API
for fuel api
URL in Next JS App = `http://localhost.com/fuelStation`
query URL called = `http://localhost.com/fuelStation?keyword=AbcfuelStation`
Data returned =

  {
    "rate": 50,
    "quantity": 100,
    "amount": 5000,
    "fuelStationName": "Abc fuel Station"
  },
  // Why this is below one? /
  {
    "rate": 50,
    "quantity": 100,
    "amount": 5000,
    "fuelStationName": "XYZ"
  }