Migrate large json file into Mongodb using nodejs

I’m using nodejs to migrate data into mongodb, the json file which i’m trying to migrate is too large, when I try to migrate just some data (about 8000 docs), it works, otherwise I’m getting this issue :

MongooseError: Operation `products.insertOne()` buffering timed out after 10000ms

at Timeout.<anonymous> (migration- 
modulenode_modulesmongooselibdriversnode-mongodb-nativecollection.js:148:23)

at listOnTimeout (internal/timers.js:557:17)

at processTimers (internal/timers.js:500:7)

MongooseError: Operation `products.insertOne()` buffering timed out after 10000ms

 at Timeout.<anonymous> (migration- 
modulenode_modulesmongooselibdriversnode-mongodb-nativecollection.js:148:23)

at listOnTimeout (internal/timers.js:557:17)

at processTimers (internal/timers.js:500:7)

the script :

/** @format */
fs = require('fs')
var mongoose = require('mongoose')
 mongoose.connect('mongodb://host')
 mongoose.Promise = global.Promise
 var schema = new mongoose.Schema({
 //some fields
  })
  var d = fs.readFileSync('./data/file.json', 'utf8', (err, data) => {
   if (err) throw err
   return d
   })
  var e = JSON.parse(d)
  var Product = mongoose.model('product', schema)
  //console.log(e)
  for (var i = 0; i < e.length; i++) {
   // data process
   // another data process
  var product = new Product(e[i])
  product.save(function (err) {
  if (err) return console.log(err)
  })
 }
 e.length === i ? console.log('Migration Done successfully') : ''

any solution to get ride of this problem please ?

My js code is not working can anyone find error

There are many <li/> with class name list and one having active too and I wanna give active class name to <li/> on clicking

const list = document.querySelectorAll('.list');

function activeLink(){
    list.forEach((element) =>
      element.classList.remove('active')
    );
    this.classList.add('active')
}

list.forEach((element) => 
  element.addEventListener('click',activeLink)
)

how do I load more on one image at once from this API, and display it in a grid?

I essentially want the page to initially load with a total of 9 images from this api. If I add another image, and retrieve it on page load, it displays a duplicate, and only when I fetch the api again, does the api make a random call, and load a new image.

Right now, on page load, one image is displayed, with text retrieved from the json object and stored in a parapragh.

My end goal is to have the page load with 9 different images of the dogs, and have a button that fetches the json data for each unique dog, so all images will be linked to a unique button.

I’m having trouble wrapping my head around a few of the concepts, and React is very new to me.

App.js

import './App.css';
import './Dog.js';
import FetchAPI from './FetchAPI';




function DogApp() {

  return (
    <div className="DogApp">
     <FetchAPI />
    </div>
  );
}

export default DogApp;

FetchAPI.js

import React, { useState, useEffect } from 'react'


const FetchAPI = () => {

    const [data, setData] = useState([]);

    const apiGet = () => {
        const API_KEY = "";
        fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
            .then((response) => response.json())
            .then((json) => {
                console.log(json);
                //setData([...data,json]); if json is single object
                setData([...data, ...json]); // if json is array of one object then use this line
            });
    };


    useEffect(() => {           //call data when pagee refreshes/initially loads 
        apiGet();


    }, []);

    return (
        <div>
            {data.map((item) => (
                <div class="dog">
                    <img src={item.url}></img>
                    <button onClick={apiGet}>Fetch API</button>
                </div>
            ))}
            {data.map((item) => (
                <p>{JSON.stringify(item.breeds)}</p>
            ))}


            {/*<pre>{JSON.stringify(data, null, 2)}</pre> */}
            <br />


        </div>

    )
}

export default FetchAPI;

Change background-position with scroll and mouse whell up/down with animeJS

I want to change the background-position when scrolling, when scrolling up, a reverse is done, when scrolling down, the usual animation is played. I need full paste scrolling. I need to define scrolling with scroll and mouse wheel. At the moment, I only have a scroll, but for some reason the animation only happens when the scroll is completed and not at the time of the scroll.

CodeSandbox

Get access token using Refresh token through google API using NodeJS

when the callback URL is called I am getting the token from google API and store it in MongoDB.

exports.authorizedGoogle = async (req, res, next) => {
  const oauth2Client = new google.auth.OAuth2(
    process.env.GOOGLE_CLIENT_ID,
    process.env.GOOGLE_CLIENT_SECRET,
    process.env.GOOGLE_CALLBACK_URL
  );
  
    const code = req.query.code;
    const userId = req.query.state;
    const { tokens } = await oauth2Client.getToken(code);
    oauth2Client.setCredentials(tokens);
    var oauth2 = google.oauth2({
      auth: oauth2Client,
      version: "v2",
    });
    const { data } = await oauth2.userinfo.get();
    if (data && tokens && code && userId) {
      const googleUser = await GoogleAccount.create({
        refreshToken: tokens.access_token,
        id_token: tokens.id_token,
        isActive: true,
        user: userId,
        name: data.name,
        email: data.email,
        googleId: data.id,
        imageLink: data.picture,
      });
      res.status(200).json({ status: "success" });
    }
};

now when I am trying to get the access token using refresh token and google API it’s throwing an error ” token has been expired or revoked”.

const currentGoogleAccount = await GoogleAccount.findOne({
      user: userId,
      isActive: true,
    });


    const oauth2Client = new google.auth.OAuth2(
      process.env.GOOGLE_CLIENT_ID,
      process.env.GOOGLE_CLIENT_SECRET,
      process.env.GOOGLE_CALLBACK_URL
    );

     oauth2Client.setCredentials({
      refresh_token: currentGoogleAccount.refreshToken,
    });

    const drive = google.drive({
      version: "v3",
      auth: oauth2Client,
    });

How to save like or dislike to database? [closed]

I’m student now, for build a website for my project, i need to archive like and dislike from comment on my website to database, it’s look like a like or dislike was show on a line of user’s database, I can create like/dislike system but i can’t save them for manage.

chrome runtime sendmessage firing multiple times

So i am new to creating chrome extensions and i am stuck on a problem for a while.

So what i am trying to do is
1 : reading urls from a page and then open them one by one
2 : so once the first url is loaded , it will click a button on that loaded url
3 : on button click it will load another page
4 : wait on that page for 5 seconds.
5 : close both pages and do the same thing for remaining url.

So it goes like

5 urls
first open -> mid page -> final page -> wait 5 sec -> close mid and final page -> check if urls are empty : if not empty do the process again

now the problem i am getting is

it loads the first mid page to final page correctly
On second it loads the mid page twice so the final page also loads twice
On third it loads the mid page thrice
On forth it loads it four times

I am not sure what i am doing wrong here.

Here is the code

**Manifest.json**

{
    "name" : "list",
    "description" : "extract url from link and open",
    "version" : "1.0",
    "manifest_version" : 3,
    "background" : {
        "service_worker" : "background.js"
    },
    "content_scripts": [{ 
        "matches": ["http://*/*", "https://*/*"],
        "all_frames": false,
        "run_at": "document_end", 
        "js": ["content.js"] 
    }],
    "permissions" : ["storage","activeTab","scripting","tabs"],
    "action" : {
        "default_popup" : "popup.html"
    },
    "host_permissions": [
      "urls"
    ]
}


**Background.js**
chrome.runtime.onInstalled.addListener(()=>{
    console.log('Extension Running');
    chrome.storage.local.set({ "closingTabQueue" : []  , "mid_url" : [] ,"loadingType" : "" ,"on_going_process" : false ,"manualHit" : true});
})



chrome.tabs.onCreated.addListener(function(tab){
    chrome.storage.local.get(null, function(items){
        if(items.manualHit==false){
            chrome.storage.local.set({ "manualHit" : true} , ()=>{
                chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
                    if(changeInfo.status=='complete'){
                        let url=tab.url
                        if(items.loadingType=='to_final_page'){
                            chrome.tabs.sendMessage(tab.id, { mssg: "waitAndClose" , tabId : tabId } );
                        }else  if(items.loadingType=="mid_url"){
                          chrome.storage.local.set({ "manualHit" : false , "loadingType" : "to_final_page" } ,()=>{
                                chrome.tabs.sendMessage(tab.id, { mssg: "clickBtn" , tabId : tabId } );
                          });
                        }
                    }
                })  
            });
        }
    });
});


chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log( request, sender )
    if (request.type === "mid_url"){
        chrome.storage.local.get(null, function(items){
            let mid_urls=items.mid_url;
            let on_going_process = items.on_going_process;
            if(on_going_process==false){
                if(mid_urls.length!=0){
                    let first_url = mid_urls[0];
                    mid_urls.shift();
                    chrome.storage.local.set({  "mid_url" : mid_urls ,"loadingType" : "mid_url" ,"on_going_process" : true} ,()=>{
                        chrome.tabs.create({"url":first_url},function(newTab) {
                            if(items.closingTabQueue==undefined){
                                chrome.storage.local.set({ "closingTabQueue" : [newTab.id] })
                                sendResponse({})
                                return
                            }else{
                                let queue = items.closingTabQueue
                                queue.push(newTab.id);
                                chrome.storage.local.set({ "closingTabQueue" : queue })
                                sendResponse({})
                                return
                            }
                        })
                    });
                }
            }
        })
    }else if (request.type === "process_completed"){
        
        const closeExisting = () => {
            return new Promise (function(resolve, reject) {


                    const closeTabs = () => {
                        return new Promise (function(resolve, reject) {
                            chrome.storage.local.get(null, function(items){
                                let openedTab = request.tabId;
                                let tabs = items.closingTabQueue
                                if(!tabs.includes(openedTab)){
                                    tabs.push(openedTab)
                                }
                                chrome.tabs.remove(tabs,()=>{
                                    return resolve('');
                                })
                            });
                        })
                    }

                    closeTabs().then(()=>{

                        chrome.storage.local.set({ "closingTabQueue" : [] ,"on_going_process" : false , "loadingType": "mid_url" ,"manualHit" : true} ,()=>{
                                        sendResponse({})
                            return resolve('')
                        });
                    })

            });
        }

        const checkNext = () => {
            return new Promise (function(resolve, reject) {
                chrome.storage.local.get(null, function(items){
                    let mid_urls=items.mid_url;
                    let on_going_process = items.on_going_process;
                    if(on_going_process==false){
                        if(mid_urls.length!=0){
                            let first_url = mid_urls[0];
                            mid_urls.shift();

                            chrome.storage.local.set({  "mid_url" : mid_urls ,"loadingType" : "mid_url" ,"on_going_process" : true} ,()=>{
                                chrome.tabs.create({"url":first_url},function(newTab) {
                                    if(items.closingTabQueue==undefined){
                                        chrome.storage.local.set({ "closingTabQueue" : [newTab.id] } , ()=>{return true})
                                        
                                    }else{
                                        let queue = items.closingTabQueue
                                        queue.push(newTab.id);
                                        chrome.storage.local.set({ "closingTabQueue" : queue } , ()=>{return true})
                                        return
                                    }
                                })
                            });
                        }else{
                            console.log('Extension Reset');
                            chrome.storage.local.set({ "closingTabQueue" : []  , "mid_url" : [] ,"loadingType" : "" ,"on_going_process" : false ,"manualHit" : true});

                        }
                    }
                })
            });
        }
        closeExisting().then(checkNext)
    }
  }
);

**content.js**
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.mssg === "clickBtn"){
    let tabId=request.tabId
    clickBtn(tabId)
  }else if(request.mssg === "waitAndClose"){
    let tabId=request.tabId
    setTimeout(()=>{
      chrome.runtime.sendMessage({type: "process_completed" , tabId : tabId}, function(response) {
        sendResponse();
        return
      });
    },5000)
  }
});

function clickBtn(tabId){
  chrome.storage.local.set({ "manualHit" : false , "loadingType" : "to_final_page" } ,()=>{
    setTimeout(()=>{
      document.getElementById("some_id").click(); // this will open a url
    },2000)
  });
}

**popup.html**
<!DOCTYPE html>
<html>
  <head>
    <!-- <link rel="stylesheet" href="button.css"> -->
  </head>
  <body>
    <button id="save">Save</button>
    <script src="popup.js"></script>
  </body>
</html>

**popup.js**
let save = document.getElementById("save");

save.addEventListener("click", async () => {

    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: saveUrl,
    });
});

function getUrl(){
    let mid_url=['www.google.com','www.facebook.com','www.instagram.com','www.stackoverflow.com'];
    for(let i of urls){
        mid_url.push(i.href);
    }
    if(mid_url.length>0){
        chrome.storage.local.set({ "manualHit" : false , "mid_url" : mid_url } ,()=>{
            chrome.runtime.sendMessage({type: "mid_url"}, function(response) {});
        });
    }
}

** Note **
I have stored variables in chrome storage local as
closingTabQueue : tabs to close after completion
mid_url : to check which variables are left
loadingType : to check is its mid page or final page
manualHit : so that onupdated complete works only when the user hit that
on_going_process : check is a url is currently being executed or not

Is there an way in cypress to assert a new tab opening without target or remove attribute as i have href as something like this?

I have the element something like this and i am writing the code something like this to click

Then('I click on the Help Icon > {string}', (option) => {
    cy.get('.icon-help').click({ force: true })
    cy.get('ul a')
        .contains(option)
        .click({ force: true })
});

as i need to click first and assert that the page is opening in the next step but the page is opening in a new tab and to remove attribute or _target there is no target attribute.Its completely opening in new tab so how i can assert that the page opening in new tab?
enter image description here

Javascript Images Cycle on Hover

I’m new to coding and would like to adapt a code I got from CodePen for my website.
It is to hover over an image and the images below will automatically cycle.
However this code works for only one set of images and doesn’t work if I have two sets of images.
I would really like to learn why please??? Thank you.

<html>
<style>
.js-animated figure.active {
  opacity: 1;
}

.image-deck {
  position: relative;
  height: 12rem;
  width: 18rem;
}

.image-deck figure {
  opacity: 0;
  height: 100%;
  width: 100%;
  position: absolute;
}

.image-deck figure img {
  height: 100%;
  width: 100%;
}
</style>

<body>
    <!--Working-->
    <div class="image-deck js-animated">
        <figure>
            <img src="https://picsum.photos/300/300">
        </figure>
        <figure>
            <img src="https://picsum.photos/301/301">
        </figure>
        <figure>
            <img src="https://picsum.photos/302/302">
        </figure>
        <figure>
            <img src="https://picsum.photos/303/303">
        </figure>
    </div>
    
    <!--Not Working-->
    <div class="image-deck js-animated">
        <figure>
            <img src="https://picsum.photos/304/304">
        </figure>
        <figure>
            <img src="https://picsum.photos/305/305">
        </figure>
        <figure>
            <img src="https://picsum.photos/306/306">
        </figure>
        <figure>
            <img src="https://picsum.photos/307/307">
        </figure>
    </div>
</body>

<script>
    // get the image wrapper
    const imageDeck = document.querySelector(".image-deck.js-animated");

    // get the set of images within the wrapper
    const images = imageDeck.children;

    // reveal the first image
    images[0].classList.add("active");

    // set up the iterator
    let i = 0;

    // set up the function that we will call from our repeater
    function cyclePhotos() {

        // remove the active class from the current image
        images[i].classList.remove("active");

        // if the iterator is less than the total number of images
        // go to the next number, otherwise reset to 0
        i = i + 1 < images.length ? i + 1 : 0;

        // add the active class to the next image
        images[i].classList.add("active");
        
    }

    // instantiate the repeater
    let repeater;

    // when you hover over the image wrapper, start the reapeater
    // repeat every 500ms
    imageDeck.addEventListener("mouseover", (e) => {
        repeater = setInterval(cyclePhotos, 500);
    });

    // when you are no longer hovering, clear the repeater
    imageDeck.addEventListener("mouseout", (e) => {
        clearInterval(repeater);
    });
</script>

</html>

why warpping your code in resolved prop makes your sync code act like async code?

loop in side of the promise works like sync code for example


console.log('im working')
function proLoop(){
    return new Promise((resolve ,rejects)=>{
        for (let i = 0; i < 1000000000000; i++) {}
        console.log('loop is done')
    })
}

proLoop();

console.log('im working')

So even if we write is like promise it will get more time and freezes our code In other words it will works synchronically.

i find a solution but why it works?

so the solution is just warp your code as like resolved promise

like this

return Promise.resolve().then( ()=>{
    for (let i = 0; i < 1000000000000; i++) {}
    console.log('loop is done')
})

but why and how???

prevent default not working on form submission

trying to prevent default on form submission though it goes ahead and submits user input–
if I have the form onsubmit value to empty then the form prevents default.. is there solution to this?

Below is my form; on submit is empty as it prevents default when empty. though it should be going to generate as shown below…

              <form className='grid' onSubmit={}>
                <div className='flex'>
                  {/* <InputField
                    isRequired={true}
                    id='productNameField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg h-full'
                    type='text'
                    placeholder='Spotify'
                    label='Product Name'
                    onChange={onSetProductName}
                  /> */}

                  <div className=' relative '>
                    <label className='text-gray-700'>
                      Product Name
                      <span className='text-red-500 required-dot'>*</span>
                    </label>
                    <input
                      type='text'
                      required
                      className=' rounded-lg border-transparent flex-1 appearance-none border border-gray-400 w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-sm text-base focus:outline-none focus:ring-2 focus:ring-accent1 focus:border-transparent'
                      placeholder='Spotify'
                      onChange={onSetProductName}
                    />
                  </div>
                </div>
                {/* <div className='flex pt-6'>
                  <InputField
                    id='productDescriptionField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg resize-none h-full p-1'
                    type='text'
                    placeholder='Spotify is a music service that lets you listen to music and share it with friends.'
                    label='Product Description'
                    maxRows={5}
                    onChange={onSetProductDescription}
                    multiline
                  />
                </div>
                <div className='flex pt-6'>
                  <InputField
                    id='platformField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg h-full'
                    type='text'
                    placeholder='Instagram'
                    label='Platform'
                    onChange={onSetPlatform}
                  />
                </div>
                <div className='flex pt-6'>
                  <InputField
                    id='audienceField'
                    required={true}
                    className='border-solid border-2 border-gray-200 pl-3 w-full rounded-lg h-full'
                    type='text'
                    placeholder='Teens'
                    label='Audience'
                    onChange={onSetAudience}
                  />
                </div> */}
                <div className='grid'>
                  <div className='grid grid-cols-2 pt-6'>
                    {pendingCreativeAd === true ? (
                      <div className='grid justify-start'>
                        <button
                          type='button'
                          disabled={true}
                          className='py-2 px-4 flex justify-center items-center bg-gray-600 text-white w-full transition ease-in duration-200 text-center text-base font-semibold rounded-lg '
                        >
                          1 sec.
                          <LoadingIcon height={21} width={21} />
                        </button>
                      </div>
                    ) : (
                      <div className='grid justify-start'>
                        <button
                          type='submit'
                          // onClick={generate}
                          className='py-2 px-4 flex justify-center items-center  bg-accent1 hover:bg-blue-800 focus:bg-accent1 text-white w-full transition ease-in duration-200 text-center text-base font-semibold shadow-md focus:outline-none rounded-lg  '
                        >
                          Generate
                        </button>
                      </div>
                    )}
                    <div className='grid justify-end'>
                      <button
                        type='button'
                        onClick={clearForm}
                        className='py-2 px-4 flex justify-center items-center  bg-orange-700 hover:bg-orange-800 text-white w-full transition ease-in duration-200 text-center text-base font-semibold shadow-md focus:outline-none focus:bg-orange-700  rounded-lg  '
                      >
                        Clear Form
                      </button>
                    </div>
                  </div>
                </div>
              </form>
 const generate = async (e) => {
    e.preventDefault();
    startGenAd(productName, productDescription, platform, audience);
    console.log('submitting generate');
  };

Javascript Multiple Timelines visualizer and selector

Currently I have build this website which I would like to extend. The component I am trying to build takes as input a list of date arrays and visualizes them above an accurate timeline. The user should be able to select from the time steps on the master timeline so I can use the new date array for another component. I would love for the component to allow the user to use a double range slider which would capture all time steps in the range that all the layers have in common. I have other ideas but I want to find out if there is a library which would help me with such a component as I am using Vuetify at the moment and the options like Timemap.js or Timeline.js are not evidently applicable to my case it seems. Any suggestions are welcome, I am just trying to learn and build this. rough diagram of what I am trying to build

JavaScript Scroll Animation (ScrollMagic)

Have been watching some tutorials and testing out the ScrollMagic feature with GASP, yet this animation won’t work on my page (object is sticky). Pretty new to coding, so likely a simple solution to this. Thanks

const flightPath = {
    curviness: 1,
    autoRotate: true,
    values: [
        { x: 100, y: -30},
        { x: 300, y: 90},
    ]
}
const tweet = new TimelineLite();

tweet.add(
    TweenLite.to(".item", 1, {
        bezier: flightPath,
        ease: Power1.easeInOut
    })
);

HTML

<section> 
  <img class="item" src="images/paper.png" alt="img">
</section>


<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/animation.gsap.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/debug.addIndicators.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenLite.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TimelineLite.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/CSSPlugin.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/BezierPlugin.min.js" ></script>

<script> src="app.js"</script>   



CSS


.item {
    height: 60px;
    position: relative;
    top: 50%;
    left: 0;
}