How to find document’s array item by its “_id” field in MongoDB (Mongoose)?

I have the following schema (NestJS + Mongoose):

@Schema({ timestamps: true })
export class Listing {
  @Prop({
        type: [{
            bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true },
            amount: { type: Number, required: true },
            date: { type: Date, required: true }
        }],
        select: false
    })
        bids!: Bid[]
}

so basically every listing document has an array of bids.
now I notice that automatically mongoDB (or mongoose) creates _id field for every bid item I put into the bids array.

My question is, If I have a bid’s _id, how can I query it’s item from the listing’s bids array? something like:

  // Adding a new bid to the listing, and retrieving the updated listing
  const listingWithAddedBid = await this.listingModel.findByIdAndUpdate(listingId, {
    $push: {
        bids: {
            $each: [{
                amount: bidInfo.amount,
                bidderId: new Types.ObjectId(user.id),
                date: new Date()
            }],
            $sort: { amount: -1 }
        }
    }
}, { new: true })

  // Getting the new bid's _id from the array (it will be at index 0 because we sort buy amount)
  const newBidId = listingWithAddedBid.bids[0]._id

  // here how can I query the entire bid item from the array with 'newBidId'? this won't work
  this.listingModel.findById(newBidId) // returns null

Export or import trouble with jsx files

I try to import some components into my App.js file from index2.js(export .jsx collection) where I can import only one component to see something on website – when I want import more, the page is white / empty, but if I import only Navbar.jsx component that’s work.

File structure:

__node_modules

__public

__src
____components
_______Cryptocurrencies.jsx
_______Cryptodetails.jsx
_______index2.js
_______Exchanges.jsx
_______Homepage.jsx
_______Navbar.jsx
_______News.jsx
___App.css
___App.js
___index.js

__.gitignore
__package-lock.json
__package.json

index.js:

import react from "react";
import reactDom from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App"
import 'antd/dist/antd.min.css';
reactDom.render(
    <Router>
        <App />
    </Router>, 
    document.getElementById('root')
)

App.js

import React from 'react'
import { Routes, Route, Link } from 'react-router-dom'
import { Layout, Typography, Space } from 'antd'
import { Cryptocurrencies, Cryptodetails, Exchanges, Homepage, Navbar, News } from './components'
import './App.css';

const App = () => {
    return (
        
            <div className='app'>
                <div className='navbar'>
                    <Navbar />
                </div>
                <div className='main'>
                <Layout>
                    <div className='routes'>
                        <Routes>
                            <Route path='/'>
                                <Homepage />
                            </Route>
                            <Route path='/exchanges'>
                                <Exchanges />
                            </Route>
                            <Route path='/cryptocurrencies'>
                                <Cryptocurrencies />
                            </Route>
                            <Route path='/crypto:coinId'>
                                <Cryptodetails />
                            </Route>
                            <Route path='/news'>
                                <News />
                            </Route>
                        </Routes>
                    </div>
                </Layout>
            </div>
                <div className='footer'>

                </div>
            </div>
        
    )
}

export default App

index2.js

export { default as Cryptocurrencies } from './Cryptocurrencies'
export { default as Cryptodetails } from './Cryptodetails'
export { default as Exchanges } from './Exchanges'
export { default as Homepage } from './Homepage'
export { default as Navbar } from './Navbar'
export { default as News } from './News'

The .jsx files are created by using default rafce.

Not working code (App.js):

...
import { Cryptocurrencies, Cryptodetails, Exchanges, Homepage, Navbar, News } from './components'
...
uncommented code with Layout part in div ``main`` class
...

Working code (App.js):

...
import { Navbar } from './components'
...
//commented code with Layout part in div ``main`` class
...

Please, explain me where have make an error. Thanks!

Is it possible to have nested enum in Typescript?

Having those enums:

export enum First {
  TEST_1 = 'test_1',
  TEST_2 = 'test_2'
}

export enum Second {
  TEST_3 = 'test_3',
  TEST_4 = 'test_4'
}

is it possible to combine them into a single one?

Something like:

export enum Main {
  First {
    TEST_1 = 'test_1',
    TEST_2 = 'test_2'
  },
  Second {
    TEST_3 = 'test_3',
    TEST_4 = 'test_4'
  }
}

React – Sending uploaded images as url to an API

I am sending multiple images to an API but the way I do it sends it as an object but I need to send it as a URL.

State:

const [files, setFiles] = useState([]);

Image uploader:

 const fileSelectHandler = (e) => {
        setFiles([...files, ...e.target.files]);
      };

<input
  type="file"
  className="form-control"
  id="customFile"
  multiple
  onChange={fileSelectHandler}
/>

Expected sending package:

"pic": [
            {
                "url": "760634d2-f8ec-4caa-9a2d-14a8828cfb5dpetplace.jpg"
            },
            {
                "url": "760634d2-f8ec-4caa-9a2d-14a8828cfb5dpetplace.jpg"
            }
       ]

Why is my WebRTC peer-to-peer application failing to work properly?

it’s been quite a long time since I’ve posted here. Just wanted to bounce this off of you as it has been making my brain hurt. So, I have been developing a real time video chat app with WebRTC. Now, I know that the obligatory “it’s somewhere in the network stack (NAT)” answer always applies.

As is always the case it seems with WebRTC, it works perfectly in my browser and on my laptop between tabs or between Safari/Chrome. However, over the internet on HTTPS on a site I’ve created, it is shotty at best. It can accept and display the media stream from my iPhone but it cannot receive the media stream from my laptop. It just shows a black square on the iPhone for the remote video.

Any pointers would be most appreciate though as I’ve been going crazy. I know that TURN servers are an inevitable aspect of WebRTC but I’m trying to avoid employing that.

So, here is my Session class which handles essentially all the WebRTC related client side session logic:

(The publish method is just an inherited member that emulates EventTarget/EventEmitter functionality and the p2p config is just for Google’s public STUN servers)

class Session extends Notifier {
    constructor(app) {
        super()

        this.app = app

        this.client = this.app.client

        this.clientSocket = this.client.socket

        this.p2p = new RTCPeerConnection(this.app.config.p2pConfig)

        this.closed = false

        this.initialize()
    }

    log(message) {
        if (this.closed) return

        console.log(`[${Date.now()}] {Session} ${message}`)
    }

    logEvent(event, message) {
        let output = event
        if (message) output += `: ${message}`
        this.log(output)
    }

    signal(family, data) {
        if (this.closed) return
        
        if (! data) return

        let msg = {}
        msg[family] = data
        
        this.clientSocket.emit("signal", msg)
    }

    initialize() {
        this.p2p.addEventListener("track", async event => {
            if (this.closed) return
            try {
                const [remoteStream] = event.streams
                this.app.mediaManager.remoteVideoElement.srcObject = remoteStream
            } catch (e) {
                this.logEvent("Failed adding track", `${e}`)
                this.close()
            }
        })

        this.p2p.addEventListener("icecandidate", event => {
            if (this.closed) return 
            if (! event.candidate) return
            this.signal("candidate", event.candidate)
            this.logEvent("Candidate", "Sent")
        })

        this.p2p.addEventListener("connectionstatechange", event => {
            if (this.closed) return
            switch (this.p2p.connectionState) {
                case "connected":
                    this.publish("opened")
                    this.logEvent("Opened")
                    break
            
                // A fail safe to ensure that faulty connections 
                // are terminated abruptly
                case "disconnected":
                case "closed":
                case "failed":
                    this.close()
                    break

                default:
                    break
            }
        })

        this.clientSocket.on("initiate", async () => {
            if (this.closed) return
            try {
                const offer = await this.p2p.createOffer()
                await this.p2p.setLocalDescription(offer)
                this.signal("offer", offer)
                this.logEvent("Offer", "Sent")
            } catch (e) {
                this.logEvent("Uninitiated", `${e}`)
                this.close()
            }

        })

        this.clientSocket.on("signal", async data => {
            if (this.closed) return
            try {
                if (data.offer) {
                    this.p2p.setRemoteDescription(new RTCSessionDescription(data.offer))
                    this.logEvent("Offer", "Received")
                    const answer = await this.p2p.createAnswer()
                    await this.p2p.setLocalDescription(answer)
                    this.signal("answer", answer)
                    this.logEvent("Answer", "Sent")
                }

                if (data.answer) {
                    const remoteDescription = new RTCSessionDescription(data.answer)
                    await this.p2p.setRemoteDescription(remoteDescription)
                    this.logEvent("Answer", "Received")
                }

                if (data.candidate) {
                    try {
                        await this.p2p.addIceCandidate(data.candidate)
                        this.logEvent("Candidate", "Added")
                    } catch (e) {
                        this.logEvent("Candidate", `Failed => ${e}`)
                    }
                }
            } catch (e) {
                this.logEvent("Signal Failed", `${e}`)
                this.close()
            }
        })

        this.app.mediaManager.localStream.getTracks().forEach(track => {
            this.p2p.addTrack(track, this.app.mediaManager.localStream)
        })
    }

    close() {
        if (this.closed) return

        this.p2p.close()
        this.app.client.unmatch()
        this.logEvent("Closed")
        
        this.closed = true
    }
}

VueJS: JSON objects are not showing in my code

I have API that stores JSON data as shown in JSON body below… I wanted to show the data amount stored in installments but it didn’t work good because its showing me each amount value two times and I couldn’t figure out the problem here.

{
  "response": [{
        "floors": [{
              "flats": [{
                    "status": "sold",
                    "price": "150000",
                    "currency": "USD",
                    "end_date": "Not Set",
                    "buyer": "ella",
                    "buyer_phone_number": "002822128",
                    "receipt_number_field": "553108012022",
                    "size_unit": "M",
                    "_id": "61d9b61397e87e39832a5abb",
                    "flat_number": 1,
                    "description": "This is a newly created flat.",
                    "city": "NY",
                    "payment": {
                      "installment_payment": {
                        "installments": [{
                            "amount": "1344",
                            "date": "2022-01-13",
                            "is_paid": false
                          },
                          {
                            "amount": "444",
                            "date": "2022-01-24",
                            "is_paid": false
                          },
                          {
                            "amount": "44444",
                            "date": "2022-01-17",
                            "is_paid": false
                          }
                        ],
                        "remaining": "150000"
                      },
                      "paid_amount": "1234"
                    },
                    "floor": "61d9b61397e87e39832a5aba",
                    "building": "61d9b61397e87e39832a5ab9",
                    "size": "176.25",
                    "directions": " south",
                    "createdAt": "2022-01-08T16:04:43.557Z",
                    "updatedAt": "2022-01-08T16:22:29.220Z",
                    "__v": 0
                  },

my code:

<div v-for="(flat,index) in Flats" :key="index">
<div v-for="(find,indexT) in flat.payment" :key="indexT" >
<div v-if="flat.payment.installment_payment">
 <div v-for="(find,indexT) in  flat.payment.installment_payment.installments" :key="indexT">
                <div v-if="find.amount >0">

                 <p> {{find.amount}}$  amount </p>
                                         
                                      </div>
                                      </div>
                                    </div>
                                </div>
                                </div>

p.S: I stored my API data in array Flats

How to make images responsive on smaller screen sizes?

I am a beginner learning from tutorials and I am using the NASA APOD API to make an image gallery.

However, for some reason the images are not responsive when viewing on smaller screen sizes. The images goes off screen and I want it to be like a grid 3 column gallery.

Is using flex box the answer? or Perhaps using media queries is easier?

Apologies for the newbie question.

const resultsNav = document.getElementById("resultsNav");
const favoritesNav = document.getElementById("favoritesNav");
const imagesContainer = document.querySelector(".images-container");
const saveConfirmed = document.querySelector(".save-confirmed");
const loader = document.querySelector(".loader");

// NASA API
const count = 18;
const apiKey = 'DEMO_KEY';
const apiUrl = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}&count=${count}`;

let resultsArray = [];
let favorites = {};

// Show Content
function showContent(page) {
  window.scrollTo({ top: 0, behavior: "instant" });
  if (page === "results") {
    resultsNav.classList.remove("hidden");
    favoritesNav.classList.add("hidden");
  } else {
    resultsNav.classList.add("hidden");
    favoritesNav.classList.remove("hidden");
  }
  loader.classList.add("hidden");
}

// Create DOM Nodes
function createDOMNodes(page) {
  const currentArray =
    page === "results" ? resultsArray : Object.values(favorites);
  currentArray.forEach((result) => {
    // Card Container
    const card = document.createElement("div");
    card.classList.add("card");

    // Link that wraps the image
    const link = document.createElement("a");
    link.href = result.hdurl;
    link.title = "View Full Image";
    link.target = "_blank";

    // Image
    const image = document.createElement("img");
    image.src = result.url;
    image.alt = "NASA Picture of the Day";
    image.loading = "lazy";
    image.classList.add("card-img-top");

    // Card Body
    const cardBody = document.createElement("div");
    cardBody.classList.add("card-body");

    // Card Title
    const cardTitle = document.createElement("h5");
    cardTitle.classList.add("card-title");
    cardTitle.textContent = result.title;

    // Save Text
    const saveText = document.createElement("p");
    saveText.classList.add("clickable");
    if (page === "results") {
      saveText.textContent = "Add To Favorites";
      saveText.setAttribute("onclick", `saveFavorite('${result.url}')`);
    } else {
      saveText.textContent = "Remove Favorite";
      saveText.setAttribute("onclick", `removeFavorite('${result.url}')`);
    }

    // Card Text
    const cardText = document.createElement("p");
    cardText.textContent = result.explanation;

    // Footer Conatiner
    const footer = document.createElement("small");
    footer.classList.add("text-muted");

    // Date
    const date = document.createElement("strong");
    date.textContent = result.date;

    // Copyright
    const copyrightResult =
      result.copyright === undefined ? "" : result.copyright;
    const copyright = document.createElement("span");
    copyright.textContent = ` ${copyrightResult}`;

    // Append everything together
    footer.append(date, copyright);
    // cardBody.append(cardTitle, saveText, cardText, footer); //hide to make image display
    link.appendChild(image);
    card.append(link);

    // Append to image container
    imagesContainer.appendChild(card);
  });
}

// Update the DOM
function updateDOM(page) {
  // Get favorites from local storage
  if (localStorage.getItem("nasaFavorites")) {
    favorites = JSON.parse(localStorage.getItem("nasaFavorites"));
  }
  imagesContainer.textContent = "";
  createDOMNodes(page);
  showContent(page);
}

// Get 10 images from NASA API
async function getNasaPictures() {
  // Show Loader
  loader.classList.remove("hidden");
  try {
    const response = await fetch(apiUrl);
    resultsArray = await response.json();
    updateDOM("results");
  } catch (error) {
    // Catch Error Here
  }
}

// Add result to favorites
function saveFavorite(itemUrl) {
  // Loop through the results array to seelct favorite
  resultsArray.forEach((item) => {
    if (item.url.includes(itemUrl) && !favorites[itemUrl]) {
      favorites[itemUrl] = item;
      // Show save confirmation for 2 seconds
      saveConfirmed.hidden = false;
      setTimeout(() => {
        saveConfirmed.hidden = true;
      }, 2000);
      // Set Favorites in Local Storage
      localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    }
  });
}

// Remove item from favorites
function removeFavorite(itemUrl) {
  if (favorites[itemUrl]) {
    delete favorites[itemUrl];
    localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    updateDOM("favorites");
  }
}

// On Load
getNasaPictures();
html {
  box-sizing: border-box;
}

body {
  margin: 0;
  background: whitesmoke;
  overflow-x: hidden;
  font-family: Verdana, sans-serif;
  font-size: 1rem;
  line-height: 1.8rem;
}

.container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 5px;
  margin-bottom: 25px;
}

/* Navigation */
.navigation-container {
  position: fixed;
  top: 0;
}

.navigation-items {
  display: flex;
  justify-content: center;
}

.background {
  background: whitesmoke;
  position: fixed;
  right: 0;
  width: 100%;
  height: 60px;
  z-index: -1;
}

.clickable {
  color: #0b3d91;
  cursor: pointer;
  user-select: none;
}

.clickable:hover {
  color: #fc3d21;
}

/* Images Container */
.images-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  padding-top: 100px;
}

.column {
  margin-left: auto;
  margin-right: auto;
}

.card {
  margin: 10px 10px 20px;
  width: 300px;
  height: 300px;
}

.card-img-top {
  width: 300px;
  height: 300px;
  border-radius: 5px 5px 0 0;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.card-body {
  padding: 20px;
}

.card-title {
  margin: 10px auto;
  font-size: 24px;
}

/* Save Confirmation */
.save-confirmed {
  background: white;
  padding: 8px 16px;
  border-radius: 5px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  position: fixed;
  bottom: 25px;
  right: 50px;
  z-index: 500;
}

/* Hidden */
.hidden {
  display: none;
}
<div class="loader hidden">
    </div>

    <!-- Container -->
    <div class="container">
      <!-- Navigation -->
      <div class="navigation-container">
        <span class="background"></span>
        <!-- Results Nav -->
        <span class="navigation-items" id="resultsNav">
          <h3 class="clickable" onclick="updateDOM('favorites')">Favorites</h3>
          <h3>&nbsp;&nbsp;&nbsp;•&nbsp;&nbsp;&nbsp;</h3>
          <h3 class="clickable" onclick="getNasaPictures()">Load More</h3>
        </span>
        <!-- Favorites Nav -->
        <span class="navigation-items hidden" id="favoritesNav">
          <h3 class="clickable" onclick="getNasaPictures()">
            Load More NASA Images
          </h3>
        </span>
      </div>

      <!-- Images Container -->
      <div class="container-fluid">
        <div class="row">
          <div class="column">
            <div class="images-container"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Save Confirmation -->
    <div class="save-confirmed" hidden>
      <h1>ADDED!</h1>
    </div>

Jest/Typescript: Mock class dependencies in Jest and Typescript

I have class B which is dependent on class A. I want to test a method of class B which is internally calling a method of class A. Now, I want to unit test my method of class B by mocking class A.

My code structure:

class A {
  getSomething() {
     return "Something";
  }
}


class B {
  constructor(objectOfClassA: A) {
      this._objectOfClassA = objectOfClassA;

 }

 functionofClassBToTest() {
     const returnValueFromClassA = this.__objectOfClassA.getSomething();

     return returnValueFromClassA;
 }
}

What I have tried so far:

import ....
import { mocked } from 'jest-mock';

jest.mock("./A", () => {
    return {
        A: jest.fn().mockImplementation(() => {
            return {
                getSomething: getSomethingMock
            }
        })
    };
});

const getSomethingMock = jest.fn().mockImplementation(() => {
    return "Mock value";
});

const mockA = mocked(A, true);

test("test functionofClassBToTest", () => {
    const classBToTest = new B(mockA);

    expect(classBToTest.functionofClassBToTest.toStrictEqual("Mock value");
});


This is the error that I am getting:

TypeError: this._objectOfClassA.getSomething is not a function

Note: I don’t want to initialize an object of class A inside my test function. I only want to mock the class.

I also found some previous posts on SO : Post1 and Post2 but nothing worked.

Add transition animation when Bootstrap flex element is moved by creation of sibling

I have a simple HTML & Bootstrap element initiation as follows:

        <div class="container-fluid d-flex g-0 gap-3" id="map-div">
            <div class="row-fluid d-flex g-0 justify-content-around" id="map-row">
                <div class="d-flex g-0" id="map-col">
                    <svg id="map-svg"></svg>
                </div>
            </div>
        </div>

enter image description here

In my JavaScript, under certain conditions I add a sibling to the map-col as follows:

legend = d3.select("#map-row").insert("div")
    .attr("id", "legend-col")
    .attr("class", "g-0 fade-in shadow lh-sm")
    .style("height", "80%")
    .style("align-self", "center")

enter image description here

Is there a simple way (maybe with Bootstrap tags?) to animate the map-col transition to its new location without explicit specification, akin to "data-mdb-animation": "slide-left"?

React Bootstrap unasigned xml variable?

Hi I have 2 questions: First, in React bootstrap there is often used Xml like variable, but it has no value:

            <Bs.Modal
            show={this.state.isVisible}
            // onHide={this.props.onHide}
            scrollable={true}
            size="lg"
            aria-labelledby="contained-modal-title-vcenter"
            centered></Bs.Modal>

        

In this case its last attribute centered and I would like to ask how is this “undefined” variable called. And second question is, how to make this variable switchable, like {isCenteredtype && center}

Why my collector.on(‘collect’) event not working

client.on('messageCreate', message => {
    if(message.channel.id !== '928409019402575992') return;
    if(message.attachments.size == 0) return message.delete();
    const tik = client.emojis.cache.get('929061990721261650');
    const more = client.emojis.cache.get('929062097764110386');
    const carpi = client.emojis.cache.get('929062036468539493');
    const emojis = [
        tik,
        more,
        carpi
    ];
    message.react(tik);
    message.react(more);
    message.react(carpi);
    const filter = (r,  user) => {
        return !user.bot;
    }
    const collector = message.createReactionCollector(filter, {});
    collector.on('collect', (reaction, user) => {
        console.log(reaction);
        if(emojis.includes(reaction.emoji)){
            if(reaction.message.guild.members.cache.get(user).roles.has('909372241119162368')){
                if(reaction.emoji == tik){
                    reaction.message.member.roles.add('928409184037396520');
                } else if(reacion.emoji == more){
                    reaction.message.channel.send({ content: `${reaction.message.author} eksik bilgiler içeriyor attığın fotoğraf!` });
                } else if(reacion.emoji == carpi){
                    reaction.message.member.roles.remove('928409184037396520');
                }
            }
        }
    })
});

This is my code with discord.js@v13 it works fine to collector part but collector.on(‘collect’) event is never calling like you can see I add a console.log part to event’s start and its not triggering when I react can anyone help?(also there was a problem on normal code part so I write my code as snippet here)

Javascript Slideshow Image Container

So here is my code. I so far have the slide show worker with said given images.

The problem I am having is Containing + Stretching the images to fit inside of my container div. 🙂

Here is the code:

All help is welcome~! Thanks. ^^

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.display = "block";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}
.imgContainer {
    padding-top: 80px;
    background-color: rgba(0, 0, 0, 0.603);
    width: 100%;
    height: 575px;
}

.img1 {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover; 
}
<div class="imgContainer" alt="imgContainer">
<img class="mySlides" src="/Users/stevenjeffers/Documents/GitHub/III/images/1.jpg" alt="imgj1">
<img class="mySlides" src="/Users/stevenjeffers/Documents/GitHub/III/images/2.jpg" alt="imgj1">
<img class="mySlides" src="/Users/stevenjeffers/Documents/GitHub/III/images/3.jpg" alt="imgj1">

</div>

On off loop system on javascript [duplicate]

Hi guys my function is not working..

function onoff() {
  if(a != true){
    var a = true
    alert("System is on")
  } else if(a == true) {
    var a = false
    alert("System is off")
  }
}

And this is the html

<button type="button" id="demo" onclick="onoff()">Click Me!</button>

I couldnt figure it out how can i do it.
Thx for your helping <33