MongoDB Mongoose – saving document with ‘id’ deletes id from it

I need to save document to my db. Document has different fields and one of them “id”.

looks like this

"is_trial_product": 0,
"is_shippable": 1,
"tax_code": null,
"is_licensed": 0,
"id": 1,
"name": "Product 1",
"description": "bla bla bla",
"price": "44.9500", 

problem is when I use method Product.insertMany(…) and passing in array with my products it gets saved but deletes “id” from every document.

I’m getting results like this

"is_trial_product": 0,
"is_shippable": 1,
"tax_code": null,
"is_licensed": 0,
"name": "Product 1",
"description": "bla bla bla",
"price": "44.9500", 

I’m using this schema. Strict false and schema is empty because Product could have unpredictable fields so I don’t want to specify them for now.

const TestProductSchema = new Schema({}, { strict: false, timestamps: true }); 

I tried options like

{ id: false }
{ _id: false } 

but it didn’t help.

Maybe somebody know why is it happening and if there is a way to avoid it?

How to turn form responses objects into a 2D array with the 1st row being the header and the 2nd the answers using GAS?

Here’s how the incoming data arrives:

let e = {"authMode":"FULL","namedValues":{"Question 1":["Answer question 1"],"Question 2":["Answer question 2"],"Question 3.":["Answer Question 3"]}}

This should look like this:

[
 ["Question 1", "Question 2", "Question 3"],
 ["Answer question 1", "Answer question 2", "Answer question 3"]
]

I’ll be working on getting the headers to match the destination sheet column headers and, therefore, the object above would need to be converted to a similar format.

How can this be done using Google Apps Script? I’ve seen some example, but none found on this one precisely.

Thank you!

Using ASYNC/AWAIT untill function has finished

Alright, I have got the following 3 functions which help me collect Spotify genres based on Artists ID’s. Since most tracks on Spotify have multiple Artists, I need to combine all the individual artists genres so that I can use them at a later point.

I have the following 3 functions:

const getArtist = async (artistId) => {
  const artistObject = await getData(
    'https://api.spotify.com/v1/artists/' + artistId
  );
  if (artistObject) {
    return artistObject;
  } else {
    return 'Not found';
  }
};
const getAllGenres = (artists) => {
  let artistGenres = [];

  artists.map((item) => {
    getArtist(item.id).then((artist) => {
      artist.genres.map((genre) => {
        if (artistGenres.indexOf(genre) == -1) {
          artistGenres.push(genre);
        }
      });
    });
  });

  return artistGenres;
};

And

const getGenre = (artists) => {
  const allgenres = getAllGenres(artists);

  console.log(allgenres);
}

Whenever I check the value of allgenres in the console it looks empty but whenever I click the arrow to unfold it, it has value. I know that this is because it revalidates the value of allgenres whenever I unfold the array.

I have looked online for solutions regarding this and came across async/await. I have tried this and had to change getAllGenres into a promise. Not a problem but it did not solve the issue.

Read and use data from js file in C++

I have a C++ game project using SDL. Besides, I have a .js file for the tiled map (I attach a pastebin link for more detailed: https://pastebin.com/GKqs3km5). How can I use this to create map in my project? I try ifstream to read this file but it seems doesn’t right.

//from lesson 39 Lazyfoo
for (int i = 0; i < TOTAL_TILES; ++i)
        {
            //Determines what kind of tile will be made
            int tileType = -1;

            //Read tile from file
            js >> tileType;

            //If the was a problem in reading the map
            if (js.fail())
            {
                //Stop loading map
                printf("Error loading map: Unexpected end of file!n");
                tilesLoaded = false;
                break;
            }

            //If the number is a valid tile number
            if ((tileType >= 0) && (tileType < TOTAL_TILE_SPRITES))
            {
                tiles[i] = new Tile(x, y, tileType);
            }

CSV string to array of objects

I’m trying to convert a CSV string into an array of array of objects. Although the issue is, there is a bunch of n in the body from the incoming request, with are causing the request to split and mess up all the code. I’m attempting to fix this even with n in the body
The string looks like this, all the messages that are strings from the incoming request, starts with a " and finishes with ".

"id,urn,title,body,risk,s.0.id,s.1.id,s.2.id,a.0.id,a.1.id,a.2.id,a.3.id
n302,25,"Secure Data","Banking can save a lot of time but it’s not without risks. Scammers treat your bank account as a golden target –
it can be a quick and untraceable way to get money from younn**TOP TIPS**nn**Always read your banks rules.** These tips don’t replace your banks rules - 
in fact we fully support them. If you don’t follow their rules, you may not get your money back if you are defrauded nn**Saving passwords or allowing auto-complete.** 
Saving passwords in your browser is great for remembering them but if a hacker is able to access your computer, they will also have access to your passwords. 
When on your banking site the password box we recommend you don’t enable the auto-complete function – a hacked device means they are able to gain access using this method nn**Use a 
PIN number on your device.** It’s really important to lock your device when you’re not using it.",,2,20,52,1,2,3,4"

I have attempted to make it smaller since there is a bunch of content, but the string that comes is basically the above, The big string with is messing my code up start at Banking can save and finishes at not using it. I have several other datas that have the same type of body, and always comes inside " body ", I have been attempting to perform a function to separate the content from this CSV string, into an array of array or an array of objects.

This is what I attempted:

function csv_To_Array(str, delimiter = ",") {
      const header_cols = str.slice(0, str.indexOf("n")).split(delimiter);
      const row_data = str.slice(str.indexOf("n") + 1).split("n");
      const arr = row_data.map(function (row) {
        const values = row.split(delimiter);
        const el = header_cols.reduce(function (object, header, index) {
          object[header] = values[index];
          return object;
        }, {});
        return el;
      });

      // return the array
      return arr;
    }

Check if the selection contains graphics

I’m trying to write a script where part of it is to find out if there is an image in the objects selected, or the objects are empty shapes.

I need to check if the files of the selection are all images, all shapes or are mixed.

I’ve put together this code with alerts (the final code will not be with alerts, it’s for understanding purposes):

    if (app.selection.length == 0) {
        alert ("Nothing selected");
        }
    else {
        for (var i = 0; i < app.selection.length; i++) {
            if ((app.selection[i].graphics.length == 0) && (app.selection[i].graphics.length == 1)) {
                alert ("The files are mixed");
                }
            else if (app.selection[i].graphics.length == 1) {
                alert ("The files are images");
                }
            else if (app.selection[i].graphics.length == 0) {
                alert ("The files are shapes");
                }
            }
        }

Obviously the code is not working as intended (it works for the images and the shapes, while I already know the mixed part it’s not written correctly), since my searches have been inconclusive.

What I’m looking for is: if nothing is selected (do something), else if the files are shapes and images (do something only to the shapes), else if there are only images (do something), else if there are only shapes (do something).

Can someone give me an idea on how to do it?

Javascript – Fetch – Download a whole website

I want to download a whole website (Get the HTML) using javascript and fetch. I tried it in “Postman” and it worked. I copied the query from “Postman” and put it in javascript:

downloadButton.addEventListener("click", async () => {
var myHeaders = new Headers();
myHeaders.append("method", "get_energy_usage");
myHeaders.append("Cookie", "ug_react_xtz_player=1; _csrf=_Yy57k-wYbldEWdVrIwHw2efDY_JOzoU; static_cache_key_v2=_ver1651505054");

var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
mode:"no-cors"
};

fetch("https://tabs.ultimate-guitar.com/tab/radiohead/creep-chords-4169", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

})

The easier way (I tried both):

fetch("https://tabs.ultimate-guitar.com/tab/radiohead/creep-chords-4169", {
    mode:"no-cors",
credentials: 'include'
}).then(response => response.text())
.then(text => console.log(text))

But unfortunately, I can’t get the HTML, only a blank console log.

Thx for helping
Greetings
Lucas

Archive rows going to very bottom of sheet. Not right under last row

I have the below code working in apps script. It does what it is supposed to as in auto archiving and deleting the rows when a checkbox is selected. The only hiccup is it is archiving the rows to the very bottom of the archive sheet, not right under the last archived row. It skips a lot of blank rows for some reason.

function onEdit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == "ACTIVITY REPORT" && e.range.columnStart == 1 && e.value == "TRUE") {
    var tsh = e.source.getSheetByName("Archive");
    var target = tsh.getRange(tsh.getLastRow() + 1, 1);
    sh.getRange(e.range.rowStart, 1, 1, sh.getLastColumn()).moveTo(target);
  }
  if (sh.getName() == 'Archive' && e.range.rowStart > 1 && e.range.columnStart == 11 
&& (e.value == 'NP CND A ACCEPTED' || e.value == 'NP BACKGROUND')) {
    SpreadsheetApp.flush();
    e.range.offset(0, 16).setValue(new Date());
  }
  if (sh.getName() == 'Archive' && e.range.rowStart > 1 && e.range.columnStart == 11) 
    {
    let ops = ['NP CND A ACCEPTED', 'NP BACKGROUND', 'HIRED INTERN-SP', 'HIRED SDR- 
  SP', 'HIRED', 'HIRED INTERN', 'HIRED SDR', 'HIRED SDR', 'NP AS', 'NP LDR', 'NP CND A 
  AR', 'NP CND A OFFER', 'NO SHOW', 'NP ORL', 'NP CND A Zoom Int', 'NP CND A 1 FL'];
    if (~ops.indexOf(e.value)) {
      e.range.offset(0, 14).setValue(new Date());
    }
  }
  }

WebAudioAPI: Is it possible to specify a range for the volume from AudioWorkletProcessor?

I followed the W3C’s Documentation to implement a “vumeter” (code) using javascript’s Web Audio API specifically the AudioWorkletProcessor and AudioWorkletNode interfaces. I would like to know why is the RMS level is compared with the previous volume multiplied by a “smoothing factor” (sorry I just started learning this topic so it’s all new for me):

 // Calculate the RMS level and update the volume.
 rms = Math.sqrt(sum / samples.length);
 this._volume = Math.max(rms, this._volume * SMOOTHING_FACTOR);

Also what is the range that the volume’s variable can take? Is it possible to know so that we can assume that the volume will be a value in a 0…100 range?

Process method code:

process (inputs, outputs, parameters) {
    const input = inputs[0];
    // Note that the input will be down-mixed to mono; however, if no inputs are
    // connected then zero channels will be passed in.
    if (input.length > 0) {
      const samples = input[0];
      let sum = 0;
      let rms = 0;
      // Calculated the squared-sum.
      for (let i = 0; i < samples.length; ++i)
        sum += samples[i] * samples[i];
      // Calculate the RMS level and update the volume.
      rms = Math.sqrt(sum / samples.length);
      this._volume = Math.max(rms, this._volume * SMOOTHING_FACTOR);
      // Update and sync the volume property with the main thread.
      this._nextUpdateFrame -= samples.length;
      if (this._nextUpdateFrame < 0) {
        this._nextUpdateFrame += this.intervalInFrames;
        this.port.postMessage({volume: this._volume});
      }
    }
    // Keep on processing if the volume is above a threshold, so that
    // disconnecting inputs does not immediately cause the meter to stop
    // computing its smoothed value.
    return this._volume >= MINIMUM_VALUE;
  }

How to only display one section of content at a time instead of it stacking on itself?

I’m having trouble only displaying content within one section of my nav bar at a time. Currently as you can see it’s showing the active content (“clothing1”) nicely but when I click “clothing2” I want “clothing 1” to not show and so on.

I don’t want the content to stack on top of itself, if that makes sense.

Thanks!

document.getElementById('nav_clothing').addEventListener('click', function(){
    var secClothing = document.getElementById('sec-clothing');
    if( getComputedStyle(secClothing,null).display=='none') secClothing.style.display='block';
    else secClothing.style.display='none';
}, false);
<!--        start of list content       --> 
<ul class="navigation-bar navigation-bar-left">
           
           
<li class="active"><a href="#clothing" id="nav_clothing" data-toggle="tab" class="class2">clothing 1</a></li>
                       
<li><a href="#clothing2" id="nav_clothing2" class="class2">clothing 2</a></li>
           
<li><a  href="#clothing3" id="nav_clothing3" data-toggle="tab" class="class2">clothing 3</a></li>
      
<li><a href="#clothing4" id="nav_clothing4" data-toggle="tab" class="class2">clothing 4</a></li>
           
<li><a href="#clothing5" id="nav_clothing5" data-toggle="tab" class="class2">clothing 5</a></li>
<!--        end of list content     --> 



<!--        content when list expands       --> 
<section id="sec-clothing">
  <div class="grid-item">
     <h2>Test content </h2>
  </div>
  <div class="grid-item">
    <img src="test.svg" class="headerbarcode" id="headerbarcode" alt="test image 1">
    </div>
    <div class="grid-item">
      <img src="test2.svg" class="headertext" id="headertext" alt="test image 2">
    </div>
</section>
<!--        end of content when list expands        -->

NEDB find using variables

Im trying to find results from my menu db by using a variable that is created from checkboxes on the front end.

The Variable created in my controller is

exports.publishMenu = function (req, res) {
const dishes = '"' + req.body.lunch + '"' + ", " + '"' + req.body.dinner + '"' + ", " +
 '"' + req.body.sides + '"' + ", " + '"' + req.body.desserts + '"' + ", " + '"' + req.body.drinks + '"';
db.getMenu(dishes);
}

this outputs

“Spicy chicken & avocado wraps”, “Veggie shepherd’s pie with sweet potato mash”, “Spicy nduja arancini”, “Lemon cheesecake”, “Caramel iced latte”

Then I try to query by using the variable in the model like so

 getMenu(dishes) {
    console.log(dishes)
    
        this.db.find({ name: { $in: [dishes] }}, function (err, docs) {
        console.log(docs)
        });
}

Which produces this output in the terminal

[]

If however I substitute the variable dishes to the text output in the find to the console.log(dishes) the query will work eg

    getMenu(dishes) {
    console.log(dishes)

        this.db.find({ name: { $in: ["Spicy chicken & avocado wraps", "Veggie shepherd's pie with sweet potato mash", "Spicy nduja arancini", "Lemon cheesecake", "Caramel iced latte"] }}, function (err, docs) {
        console.log(docs)
        });
}

Why my subdirectory “/game” of the react website cannot be served from nginx?

I have a website with has one subdirectory named “/game”. There is no problem when I click the tab in navbar when I execute the website in localhost (localhost:3000/game is working!). But when I want to access using my domain address, it gives me error “404
The requested page was not found.” (mydomain/game is not working!)

What am I missing?

React Part – Navbar.js :

...

<a href="/game">
  <span>Game</span>
</a>

...

React Part – Game.js :

import React, { Component } from 'react'

export default class Game extends Component {
    render() {
        return (
            <div className='text-white text-center game'>
                GAME INFORMATION
            </div>
        )
    }
}

React Part – App.js :

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={
          <div className="App">
            <header className='Main-header'>
              <Navbar />
              <Hero />
            </header>
            <About />
            <Gallery />
            <Faq />
          </div>
        } />
        <Route path="/game" element={<Game />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Nginx Part,
after typing vi default :

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        server_name _;

        location / {
                proxy_pass http://localhost:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

How to remove an item from list and add it to another list in Javascript?

I’m trying to remove an item from a list and add the exact element to another list variable, but apparently it gets overwritten.

Here is the code :

const [data, setData] = useState(["fridge", "milk", "dog", "cryptocurrency", "school", "blockchain", "developer", "engineer", "minecraft", "prison", "scofield", "twelve" ])
const [result, setResult] = useState([])
let temp_result = []
const handleWord = (w) => {


    for (var i=data.length-1; i>=0; i--) {
        if (data[i] === w) {
            let element = data.splice(i, 1)
            setData([...data])
            temp_result.push(element[0])
            break;
        }
    }
    console.log(temp_result)
}

Please find attached an image of the console (temp_result) : at temp_result is empty, first button click I removed fridge from data and pushed it to temp_result, second button click I removed school from data and pushed it to temp_result, but the fridge element is gone.

enter image description here

How can I avoid this ? Thanks in advance !