Push objects to New Document with Mongoose and Express

Inside my model I have an array of objects. I need to insert objects to said array when creating a NEW document. I have found information on how to do it with findandupdate but I can’t find how to do it with save().

This is my model:

const PettyCashItemsSchema = Schema (
  {
    pettyCashId:{
        type: Schema.Types.ObjectId,
        ref:'PettyCash',
        required: [true, 'La Caja Chica es Obligatoria']
    },
    item: {
        type: Number,
        unique: true
    },    
    items:{
        concept: {
            type: String,
            maxlength:50,
            required: [true, 'El Concepto es obligatorio']
        },
        incomeAmount:{
            type: Number,
            maxlength:50,
            default:0,
            required: [true, 'El Ingreso es obligatorio']
        },
        expenseAmount:{
            type: Number,
            maxlength:50,
            default:0,
            required: [true, 'El Egreso es obligatorio']
        },
        description: {
            type: String,
            maxlength:50,
            required: [true, 'La Observación es obligatoria']
        },
        status: {
            type: Boolean,
            default: true,
            required: [true, 'El Estatus es obligatorio']
        }
    },
  }  
);

And I am trying this way but it never saves anything in the array of objects:

        const pettyCashId= req.params.id;

        const itemToPush = [{
            concept: req.body.concept,
            incomeAmount: req.body.incomeAmount,
            description: req.body.description,
            'createdBy':{
                uid: req.uid,
                username: req.user.username,
            }
        }];
    
        const item = new PettyCashItems( { pettyCashId, $push: { 'items': itemToPush } } );

        await item.save();

        res.json ( item ); 

Thanks!

I am new to CSS. How do I apply CSS to this JS Fetch code to alter text position, font?

New to JS. How can I apply CSS to this JS Fetch to alter test position, font? Thank you.

<!DOCTYPE html>
<html>
  <body>
    <p id="kdkz"></p>
    <script>
      let file = 'art.txt';

      const handleFetch = () => {
        fetch(file)
          .then((x) => x.text())
          .then((y) => (document.getElementById('kdkz').innerHTML = y));
      };

      setInterval(() => handleFetch(), 2000);
    </script>
  </body>
</html>

Unable to link html with JS file

That’s my html file

<!DOCTYPE html>
<html>
    <head>
        <script src="ll.js"></script>

    </head>
    <body>
        <link rel="stylesheet" href="home.css">
        
        <h1><span>Styled</span> and <span>filterable</span> select dropdown</h1>

        <form>
            <input class="chosen-value" type="text" value="" placeholder="Type to filter">
            <ul class="value-list">
              <li>Alabama</li>
              <li>Alaska</li>
              <li>Arizona</li>
              <li>Arkansas</li>
              <li>California</li>
              <li>Colorado</li>
              <li>Connecticut</li>
              <li>Delaware</li>
              <li>Florida</li>
              <li>Georgia</li>
              <li>Hawaii</li>
              <li>Idaho</li>
              <li>Illinois</li>
              <li>Indiana</li>
              <li>Iowa</li>
              <li>Kansas</li>
              <li>Kentucky</li>
              <li>Louisiana</li>
              <li>Maine</li>
              <li>Maryland</li>
              <li>Massachusetts</li>
              <li>Michigan</li>
              <li>Minnesota</li>
              <li>Mississippi</li>
              <li>Missouri</li>
              <li>Montana</li>
              <li>Nebraska</li>
              <li>Nevada</li>
              <li>New Hampshire</li>
              <li>New Jersey</li>
              <li>New Mexico</li>
              <li>New York</li>
              <li>North Carolina</li>
              <li>North Dakota</li>
            </ul>
          </form>


</body>
</html>

My CSS is linked properly.
JavaScript file (ll.js):

const inputField = document.querySelector('.chosen-value');
const dropdown = document.querySelector('.value-list');
const dropdownArray = [... document.querySelectorAll('li')];
console.log(typeof dropdownArray)
dropdown.classList.add('open');
inputField.focus(); // Demo purposes only
let valueArray = [];
dropdownArray.forEach(item => {
  valueArray.push(item.textContent);
});

const closeDropdown = () => {
  dropdown.classList.remove('open');
}

inputField.addEventListener('input', () => {
  dropdown.classList.add('open');
  let inputValue = inputField.value.toLowerCase();
  let valueSubstring;
  if (inputValue.length > 0) {
    for (let j = 0; j < valueArray.length; j++) {
      if (!(inputValue.substring(0, inputValue.length) === valueArray[j].substring(0, inputValue.length).toLowerCase())) {
        dropdownArray[j].classList.add('closed');
      } else {
        dropdownArray[j].classList.remove('closed');
      }
    }
  } else {
    for (let i = 0; i < dropdownArray.length; i++) {
      dropdownArray[i].classList.remove('closed');
    }
  }
});

dropdownArray.forEach(item => {
  item.addEventListener('click', (evt) => {
    inputField.value = item.textContent;
    dropdownArray.forEach(dropdown => {
      dropdown.classList.add('closed');
    });
  });
})

inputField.addEventListener('focus', () => {
   inputField.placeholder = 'Type to filter';
   dropdown.classList.add('open');
   dropdownArray.forEach(dropdown => {
     dropdown.classList.remove('closed');
   });
});

inputField.addEventListener('blur', () => {
   inputField.placeholder = 'Select state';
  dropdown.classList.remove('open');
});

document.addEventListener('click', (evt) => {
  const isDropdown = dropdown.contains(evt.target);
  const isInput = inputField.contains(evt.target);
  if (!isDropdown && !isInput) {
    dropdown.classList.remove('open');
  }
});

How can I link they properly? I have tried adding

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

at multiple other places like in form tag, in body tag but it doesn’t work. I tested JS, HTML and CSS on JsBin it works perfectly just the problem is in linking these files together.

Why does my recursive search function keep returning undefined? [duplicate]

I’m trying to find the maximum area of an island within a matrix full of zeros or ones. Within this example:

My matrix would return 4 as the biggest island is made up of 4 ones.

[1,1,1],
[1,0,0],
[0,1,1]

When I’m calling my dfs function, I need to return the area of that island. At the same time, we’re converting all the ones that made up that island to zeros.

For some reason my variable “areaOfIsland” keeps receiving undefined from the function and I can’t figure out why? I’m learning recursion, BFS and DFS hoping someone can pinpoint what I’m missing here.


var maxAreaOfIsland = function (grid) {
  let maxArea = 0;

  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[0].length; j++) {
      if (grid[i][j] === 1) {
        let areaOfIsland = dfs(grid, i, j);
        console.log(areaOfIsland); //this keeps logging undefined.
        if (areaOfIsland > maxArea) {
          maxArea = areaOfIsland;
        }
      }
    }
  }

  return maxArea;
};

const dfs = (matrix, i, j, area) => {
  if (
    i < 0 ||
    j < 0 ||
    i >= matrix.length ||
    j >= matrix[0].length ||
    matrix[i][j] === 0
  ) {
    return area;
  }
  if (!area) area = 1;
  area += 1;
  matrix[i][j] = 0;
  dfs(matrix, i + 1, j, area);
  dfs(matrix, i - 1, j, area);
  dfs(matrix, i, j + 1, area);
  dfs(matrix, i, j - 1, area);
};

Create a curved text around an image

I modified the following code here: Example, so that I can create the following image below. However, in my current implementation the image nor the drawn alphabets are shown. What could be the issue? If I comment either one; The canvas or the Image it would show up but not together.

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Image {
        id: abcBar
        source: "alphabetBar.png"

        Canvas{

            property string nameFont: webFont.name

            function drawTextAlongArc(context, str, centerX, centerY, radius, angle)
            {

                context.save();
                context.translate(centerX, centerY);
                context.rotate(4 * angle / 2);
                context.rotate(-1 * (angle / str.length) / 2);
                for (var n = 0; n < str.length; n++) {
                    context.rotate(angle / str.length);
                    context.save();
                    context.translate(0, -1 * radius);
                    var char1 = str[n];
                    context.fillText(char1, 0, 0);
                    context.restore();
                }
                context.restore();

            }


          anchors.fill: parent
          onPaint: {

              var ctx = getContext("2d");
              ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
              ctx.fillRect(0, 0, width, height);


              ctx.font='50px Verdana'

              //ctx.font = '30px Courier New'
              ctx.textAlign = "center";

              var centerX = abcBar.width / 2;
              var centerY = abcBar.height/2; //height - 30;
              var angle   = Math.PI; // radians
              var radius  = 180;
              ctx.fillStyle="#000000"
              drawTextAlongArc(ctx, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", centerX, centerY, radius, angle);

          }
        }
    }
}

Illustration

How to attach button values to the input form inside?

I would like a user to either type or use the buttons to submit their calculations. I figured out the typing but I cant figure out the button on click.

  </head>
  <body class="main">
</div>
</div>
</div>
    <h1><div id="result"></div></h1>

    <input id="text" placeholder="Please type number" />
    

    <button id="equals">Calculate</button>
    <br />
    <div id="quote"></div>
     <div class="ben"><img src="7993.gif" alt=""></div>
     <button>1</button>
     <button>2</button>
     <button>3</button>
     <button>+</button>
     <button>-</button>
     <button>=</button>
  </body>
</html>

Update Global var with setInterval Not Working

I am building a game with Phaser 3. I have an ajax call I want to make every second to get player data like so:

//Var is globally declared
var player1type;

create() {


 setInterval(function() {   

        function gameWaitingroom(getWaitingroom) {      

            $.ajax({
                type: "GET",
                url: '../includes/waitingroomcheck.php',
                cache: false,
                success: getWaitingroom


            });

        }
                // resolve/success callback

                gameWaitingroom(result => { 
                    try {
                        var waitingRoomData = JSON.parse(result);
                    }
                    catch (error) {
                        console.log('Error parsing JSON:', error, result);
                    }

                    //status = waitingRoomData.statusCode;
                    player1type = waitingRoomData.player1type;
                    console.log("INSIDE INTERVAL: "+player1type);

                }); 

    },1000);

console.log("OUTSIDE INTERVAL: "+player1type);

}

My console reads like so:

INSIDE INTERVAL: user
OUTSIDE INTERVAL: undefined

Why is var player1type undefined outside of the setInterval, but it works inside just fine, even though I’ve globally declared it?

When to use and when not to use encodeURIComponent or encodeURI?

In a security standpoint, when should I use encodeURIComponent or encodeURI and when I don’t need to use it?

Do I need to use encodeURI on "https://nominatim.openstreetmap.org/search.php?q=" as shown below?


And do I need to use them on only GET or also on POST method? On another posted question, there were mixed answers.

$.get(
"https://nominatim.openstreetmap.org/search.php?q=" +
  encodeURIComponent(query) +
  "&polygon_geojson=1&format=jsonv2",
function (response) {
  if (response.length > 0) {
    var latlng = new L.LatLng(response[0].lat, response[0].lon);

    marker.setLatLng(latlng);
    map.panTo(latlng);
    acadp_update_latlng(response[0].lat, response[0].lon);
  }
},
"json"
);

Creating new JSON objects every time [duplicate]

I am trying to create a login form and the functionality I want is the following: every time the user enters his email and password, it should get stored as a new JSON object in a JSON file. Right now, what’s happening is that a single object is getting created and it is being overwritten every time the user logs in. I want a new object for every login attempt. Here is the code:

app.post("/login", validate, (req, res) => {
  let userDataArray = new Array();
  let obj = new Object();
  let email = req.body.email;
  let password = req.body.password;
  obj.email = email;
  obj.password = password;

  // const jsonString = JSON.stringify(user);
  userDataArray.push(obj);
  let jsonString = JSON.parse(JSON.stringify(userDataArray));
  fs.writeFile("data.json", JSON.stringify(jsonString), () => {
    console.log("Written to file");
  });

  res.send(`Email: ${email} Password: ${password}`);
});

How to inspect JavaScript imported classes and functions in Chrome Dev tools

When inspecting large JavaScript source files in Chrome, there are often a number of imports from modules – classes and functions. When I try and access these files directly, it seems that access is restricted. However, clearly my browser is downloading and processing the code. How can I inspect these in Chrome Dev Tools without setting breakpoints and stepping through?

Is there a way to download these files easily?

SQL to only return table values found in array values

SQL noob trying to return db results if a table value is found in an array. I’m using Node JS and Postgres.

So far, I can figure out how to return the result for a single item:

SELECT * FROM table WHERE position(value in 'someval1')>0
// returns [{ id: 1, value: 'val1' }]

I don’t know how to replace the single item above (‘someval1’) with an array.

EXAMPLE

Given the following table:

id value
1 val1
2 val2
3 val3

and the array:
['foo', 'someval1', 'anotherval2', 'bar']

how might I check that table “value” exists within each array item to return:

[
  { id: 1, value: 'val1' },
  { id: 2, value: 'val2' }
]

React / NextJs Fast refresh is not working?

My pages folder like that ;

My Pages Folder

My code is here :
employees. Page code is below , when i click add Employee button ı redirect to add-employee but lets say when i change the code add-employee.js ı take this warning message what ı have to do ?
Page is refreshing why ?


 <div className='my-4 mx-6'>
       <Link href={'/employees/add-employee'}>
          <a className='flex items-center border p-3 '>
            <AiOutlineUserAdd />
            Add Employee
          </a>
        </Link> 
      </div>

Error Message

Error message