Operation users.findOne() buffering timed out after 10000ms

I’m trying to check if a user is in my mongodb database but I keep getting an error: Operation users.findOne() buffering timed out after 10000ms. I’ve tried many things but i cant seem to get it to work. Please help.

server.js

const express = require('express');
const app = express();
const dotenv = require('dotenv').config();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const cookieParser = require("cookie-parser");

const indexRoute = require('./routes/index');
const authRoute = require('./routes/auth');

mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true }, () => {
    console.log('Connected to MongoDB');
});

app.use(express.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/views'));
app.use(express.static('Public'));
app.set('view engine', 'ejs');
app.set("views", path.join(__dirname, "views"));
app.disable('x-powered-by');

app.use('/', indexRoute);
app.use('/auth', authRoute);
app.get('/login', (req, res) => {
    res.render('login/index.ejs', {
        loginError: req.cookies['loginError'],
    });
});

app.listen(3000, () => console.log('Server Up and running'));

auth.js

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const bcrypt = require("bcryptjs");
const { loginValidation } = require('../validation');

router.post('/login', async(req, res) => {
    //Validate Data
    const { error } = loginValidation(req.body);

    if (error) {
        let msg = error.message.replace(/["]/g, '')[0].toUpperCase() + error.message.replace(/["]/g, '').slice(1) + '!';
        return res.cookie('loginError', msg, [{ httpOnly: true }]).redirect('/login');;

    }
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
        let msg = 'Invalid email or password!'
        return res.cookie('loginError', msg, [{ httpOnly: true }]).redirect('/login');;
    }


    const validPass = await bcrypt.compare(req.body.password, user.password);
    if (!validPass) {
        let msg = 'Invalid email or password!'
        return res.cookie('loginError', msg, [{ httpOnly: true }]).redirect('/login');;
    }
    const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
    res.header('auth-token', token).redirect('/dashboard');
});

module.exports = router;

.env

DB_CONNECT = not putting the url for security but this is where i have my mongodb connection url

Sorry if this is a dumb question. Any help is appreciated.

Deep copy array or object in JavaScript without data loss (no libraries) [duplicate]

I want to deep copy an object in JS without using libraries! And not JSON methods since they do not copy object methods correctly. also, not Object.assign() or spread cause they copy object properties by reference. (I’m seeking a full-depth copy with js)

//sample object---------------------------

let firstObj = {
    firstName: "Hootan",
    lastName: "Abasi Rocky",
    grade: 100,
    address: {
        city: "ahvaz",
        Street: "kian abad",
        building: {
            name: "ziba",
            number: "110",
            showNumber(){
                console.log(this.number);
            }
        },
    },
    showAddress() {
        console.log(this.address);
    },
    showFirstName: function() {
        console.log(this.firstName);
    }
};

//my function----------------------------

const deepCopy = (obj) => {
    let entries = Object.entries(obj); // [... , ["address", {city: "ahv", st: "ki"}]]

    entries.map((element, index) => {
        if (typeof element[1] === "object") {
            // {city: "ahv", st: "ki"} is object
            return deepCopy(element[1]); // return [element[0], {city: 'ahv', st: 'ki'}]
        } else {
            return element.slice();
        }
    });
    return Object.fromEntries(entries.slice());
};

//test -----------------------------------


let clone = deepCopy(firstObj);
console.log(clone.address === firstObj.address);// true: address properties have the same reference.

How to convert url to object in JavaScript

i want to change url to object like

doctor?id=k123456   => { name: 'doctor', { id: 'k123456' } }
home/doctor?id=k123456/hospital?id=h123456  => { { name: 'home' }, { name: 'doctor', { id: 'k123456' } } , { name: 'hospital', { id: 'h123456' } } }

how can i convert it?

Move component in a div to another div when clicked in react

Let’s say I have one component that only holds an image and two divs, one holding the componenet, laid out as such:

enter image description here

Upon being clicked, the component will move into the other div
enter image description here

Then when the component is clicked again, it moves back to its original spot, like such:
enter image description here

What would the logic be in order to accomplish this? Any help would be appreciated especially with code examples.

Put req working but not returning updated object with Sequelize and Express

Here is my route for updating a user using sequelize

app.put('/users/:id', async (req, res) => {
  const userId = req.params.id;
  const { userName } = req.body;
  try {
    const updatedUser = await User.update(
      { userName: userName },
      { where: { id: userId } },
      { returning: true },
      { plain: true }
    );
    res.status(200).json(updatedUser);
  } catch (err) {
    res.status(503).json({ message: err.message });
  }
})

I am still not receiving the updated user. Just an array with the number 1 inside. What am I doing wrong here?

C# – WebSocket – After sending the second message i got: A server must not mask any frames that it sends to the client

I’m receiving first message Successfully, but the second ( same message ) i got the Error :

A server must not mask any frames that it sends to the client.

Its only one client.

  private void RunWebSocketListener()
    {
        int websocket_port = 8996;
        TcpListener websocket = new TcpListener(Address, websocket_port);
        websocket.Start();
        bool websocket_isRunning = true;
        while (websocket_isRunning)
        {
            Console.WriteLine("--- Waiting for WebSocket ----");
            TcpClient websocket_client = websocket.AcceptTcpClient();
            NetworkStream sockStream = websocket_client.GetStream();
            byte[] bRead = new byte[1024];
            sockStream.Read(bRead, 0, bRead.Length);
            Console.WriteLine("---- Reading WebSocket ----");
            string websocket_header = Encoding.UTF8.GetString(bRead);

            string matchs = new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(websocket_header).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            string finakAcceptedKey = Convert.ToBase64String(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(matchs)));

            // write response
            string responseHeader = "";
            responseHeader += "HTTP/1.1 101 Switching Protocolsrn";
            responseHeader += "Connection: Upgradern";
            responseHeader += "Upgrade: websocketrn";
            responseHeader += "Sec-WebSocket-Accept: "+ finakAcceptedKey +"rn";
            responseHeader += "rn";
            byte[] sendResponse = Encoding.UTF8.GetBytes(responseHeader);
            sockStream.Write(sendResponse, 0, sendResponse.Length);

            bool clientConnected = true;
            while (clientConnected)
            {
                byte[] msg = this.encodeMessage("{ "msg": "Your message" }");
                // The Problem Writing on a Second time
                sockStream.Write(msg);
                Console.WriteLine("--- msg Sent "+ msg.Length +" Bytes ---");
                Thread.Sleep(2000);
            }
            Thread.Sleep(2000);
        }
    }

#IOException on C#:

Unable to write data to the transport connection: An established
connection was aborted by the software in your host machine..

JavaScript:

var websocket = new WebSocket("ws://LOCAL:PORT");
websocket.onopen = ....
websocket.onmessage = function(e) { console.log(e.data); }

#JavaScript Error:

failed: A server must not mask any frames that it sends to the client.
  • Do You Receive the first Message ? [ Yes i do ].
  • AcceptTcpClient To AcceptSocket [ not working ].
  • I’m using Sleep 2 seconds [ not working ].
  • new Threads [ not working ].

Map properties of an object to an object of cumulative sums

I have an object which contains some keys mapped to integers.

const obj = {'a': 1, 'b': 10, 'c': 8}

I would like to return an object which maps the same keys to the cumulative sum of previous keys.

const obj = {'a': 1, 'b': 11, 'c': 19}

I know I can do this with a loop, but I’m wondering how I would do it using the built-in array methods, such as .map() or .reduce().

Javascript – Parse string based upon keys in dictionary / object

In my React program, suppose I had the following dictionary / object

const myDict = {
    "a":"Value 1",
    "b":"Value 2",
    "hello":"Value 3",
    "Bye":"Value 4"
}

(note that no keys have values existing in any other keys – For example, no key can contain the a letter since that is a different key)

And I will be receiving a string that will ONLY CONSIST OF PERMUTATIONS OF THE KEYS TO THIS OBJECT, so, for example, possible string entries will be:

  • “abhellob”
  • “ababByeahello”
  • “ByehelloByeba”
  • etc.

And I am looking to create a function that will break the input string down into its constituent parts based upon the keys of myDict.

So, for example,

  • "abhellob" would become ["a", "b", "hello", "b"]

How can I create such a function? I’ve tried, but am getting lost with having to deal with different length keys to myDict and I don’t know how to do it.

Firebase Realtime Database rules not working on the website

I have been searching in this forum that has helped me a lot to develop my entire project in firebase but I have not been able to find the answer to my question.

I have created a small voting app where users register and can only vote if they have verified their email. Every time a user registers, a verification email is sent with the sendEmailVerification() method. Obviously I can (and I will) hide/show the UI based on user.emailVerified value (true or false) but for more security, I have configured the following rules:

{
"rules": {
  //only users can write, noone can read
  ".read": false, 
  ".write": "auth.uid != null",
    "users": {
      "$uid": {
      //Inside /users, users can read/write in child /$uid only if the $uid of the user matches with the /$uid that is the branch name    for each user
      ".read": "$uid === auth.uid", 
      ".validate": "$uid === auth.uid",
        "votos": {
        //only users that verified the email can read/write in this child object
        ".validate": "auth.token.email_verified === true",
        
        }
      }
    },

    "lists": {
    //only users that verified the email can read/write here
    //read is public because you dont need to be logged in to see the votes of the lists
    ".read": true,
    ".validate": "auth.token.email_verified == true",
    }
  }
}

I have done tests in the console simulator and everything seems to work correctly but when I go to the web it does not let me vote even though I have verified my email.

Basically I can only think of:

  • I have not configured the rules correctly (but the console simulator gives me the results I expect)
  • I have not configured the validations correctly
  • It is not enough to send the verification email. Could it be that when the user verifies the mail, a token or something should be included in the url or in the user’s data? I believe that ".validate": "auth.token.email_verified === true", is done with the true or false value of user.emailVerified of the user, but I am not an expert in this…

The only thing I’ve seen similar is problems related to user.emailVerified not being updated after clicking the verification link and this made the value always false. But again, I have no idea.

If anyone can help me, I really appreciate it. This is my first question on the forum, sorry if I did something wrong.

What is the meaning of empty export {} in vanilla javascript/HTML

In the Google Maps Javascript API example, I see they had something like this in the HTML:

<script type="module" src="./index.ts"></script>

and an empty export statement at the end of the TS/JS scripts.

let map;
function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
    });
}
window.initMap = initMap;
export {};

I don’t see any examples or mentioning of empty exports on MDN, so I was wondering if anyone knew how it works. How does the script know to run it if the export is empty.

How to have multiple dynamic forms on the same page?

I have multiple of the same inline formsets on the same page. On other pages I already have a single formset with dynamic “add” and “remove” buttons. However the javascript starts acting strange and I am unable to reuse variables among the different inline formsets.

In order to have a single dynamic from I am using:

   <script>
    document.addEventListener('click', (event) => {
        if (event.target.id === "add") {
            add_form(event)
        }
        if (event.target.id === "remove") {
            remove_form(event)
        }
    })

    function add_form(event) {
        if (event) {
            event.preventDefault()
        }
        const totalNewForms = document.getElementById('id_form-TOTAL_FORMS')
        const currentForms = document.getElementsByClassName('form')
        const currentFormCount = currentForms.length // + 1
        const formCopyTarget = document.getElementById('formset')
        const copyEmptyFormEl = document.getElementById('empty-form').cloneNode(true)
        copyEmptyFormEl.setAttribute('class', 'form')
        copyEmptyFormEl.setAttribute('id', `form-${currentFormCount}`)
        const regex = new RegExp('__prefix__', 'g')
        copyEmptyFormEl.innerHTML = copyEmptyFormEl.innerHTML.replace(regex, currentFormCount)
        totalNewForms.setAttribute('value', currentFormCount + 1)
        // now add new empty form element to our html form
        formCopyTarget.append(copyEmptyFormEl)
    }


    function remove_form(event) {
        if (event) {
            event.preventDefault()
        }
        const totalNewForms = document.getElementById('id_form-TOTAL_FORMS')
        const currentForms = document.getElementsByClassName('form')
        const currentFormCount = currentForms.length
        //const regex = new RegExp(`id_form-${currentFormCount-1}`)
        const deleteFormTarget = document.getElementById(`form-${currentFormCount - 1}`)
        totalNewForms.setAttribute('value', currentFormCount - 1)
        deleteFormTarget.outerHTML = "";
    }
</script>

I have attempted to create django context variables that are unique to each inline formset (all same parent model, different child model). I am able to set the variables but when I try to use the variables the django template does not render the javascript value of the variable, it only renders the name of the context variable I set in the views.

Example

View:

def get_context_data(self, **kwargs):
    context = super(HXUpdateView, self).get_context_data(**kwargs)
    context['formset'] = InlineFormsetFactory(
        form_kwargs={'user': self.request.user}, instance=self.object, prefix=f"{self.object.pk}-form")

    context['addButton'] = f"add-{self.object.pk}"
    context['total_forms_id'] = f"id_{self.object.pk}-form-TOTAL_FORMS"
    context['totalNewForms'] = f"totalNewForms{self.object.pk}"
    context['FormClass'] = f"{self.object}class"
    context['currentForms'] = f"currentForms{self.object.pk}"
    context['currentFormCount'] = f"currentFormCount{self.object.pk}"
    context['formCopyTarget'] = f"formCopyTarget{self.object.pk}"
    context['eFormsetId'] = f"UpdateFormset{self.object.pk}"
    context['copyEmptyFormEl'] = f"copyEmptyFormEl{self.object.pk}"
    context['emptyForm'] = f"emptyForm{self.object.pk}"
    context['regex'] = f"regex{self.object.pk}"
    context['removeButton'] = f"removeButton{self.object.pk}"
    context['deleteFormTargetId'] = f"deleteFormTargetId{self.object.pk}"
    context['deleteFormTarget'] = f"deleteFormTarget{self.object.pk}"
    context['one'] = 1

    return context

template javascript:

   <script>
        document.addEventListener('click', (event) => {
            if (event.target.id === "{{ addButton }}") {
                add_form(event)
            }
            if (event.target.id === "{{ removeButton }}") {
                remove_form(event)
            }
        })

        function add_form(event) {
            if (event) {
                event.preventDefault()
            }
            const {{ totalNewForms }} = document.getElementById("{{ total_forms_id }}");
            const {{ currentForms }} = document.getElementsByClassName('{{ FormClass }}');
            const {{ currentFormCount }} = {{ currentForms }}.length;
            const {{ formCopyTarget }} = document.getElementById('{{ FormsetId }}');
            const {{ copyEmptyFormEl }} = document.getElementById('{{ emptyForm }}').cloneNode(true);
            {{ copyEmptyFormEl }}.setAttribute('class', '{{ FormClass }}');
            {{ copyEmptyFormEl }}.setAttribute('id', `form-{{ currentFormCount }}`);
            const {{ regex }} = new RegExp('__prefix__', 'g');
            {{ copyEmptyFormEl }}.innerHTML = {{ copyEmptyFormEl }}.innerHTML.replace({{ regex }}, {{ currentFormCount }});
            {{ totalNewForms }}.setAttribute('value', {{ currentFormCount }} + 1);
            {{ formCopyTarget }}.append({{ copyEmptyFormEl }});
            console.log({{ copyEmptyFormEl }});
        }

        function removeform(event) {
            if (event) {
                event.preventDefault()
            }
            const {{ totalNewForms }} = document.getElementById('{{ total_forms_id }}');
            const {{ currentForms }} = document.getElementsByClassName('{{ FormClass }}');
            const {{ currentFormCount }} = {{ currentForms }}.length;
            //const regex = new RegExp(`id_form-${currentFormCount-1}`);
            const {{ deleteFormTarget }} = document.getElementById(`form-${currentFormCount - 1}`)

            console.log({{ deleteFormTarget }})
        }
    </script>

Having issues trying to destructure array to new variables for assignment

I am working on a project and am encountering an obstacle on something rather small. I am trying to take an array that has a string and a nested array. Remove the string assigning it to a new variable and then destructure the nested array into two new variables. I seem to be having problems as there is an undefined placeholder and I can’t seem to find a way to get around it. I think I must be messing something up simple, but I would appreciate it if you could help me understand my mistake.
Any help would be great.

Here is the code which I can’t seem to get working.

let operandArray = ['x', [1, 1]]
let temporaryArray = [];

const operator = operandArray.shift();

temporaryArray = operandArray[0];
console.log(temporaryArray);

let [operand1, operand2] = [...operandArray];
console.log(operandArray);
console.log(operand1, operand2)
.as-console-wrapper { max-height: 100% !important; }

Why does a require statement stop PHP $_POST from working?

I am using JavaScript fetch() to make a POST request to PHP in another file (file1.php), and I have it working fine. However, if I change a seemingly unrelated piece of code in a different php file, it will stop working. For example, if I add require('vendor/phpmailer/phpmailer/src/PHPMailer.php'); to the top of file2.php, the $_POST suddenly causes a 500 (internal server) error. I had a similarly random issue where the $_POST request stopped working until I moved file1.php into a different folder. The project is rather large, but below are samples of my JS and PHP files.

JavaScript.js

 url = "http://localhost/path/to/file1.php";
                fetch(url, {
                    method: "POST",
                    headers: {
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    },
                    body: `command=${"testing1"}`,
                })
              

file1.php

if($_POST['command'] == "testing1"){ 
        echo "the PHP is receiving the POSTed variable";
}

file2.php

require('vendor/phpmailer/phpmailer/src/PHPMailer.php'); //this line causes 500 error from JS to file1.php
 . . . 
//there is also a POST variable here, but listening for a different variable
if($_POST['command'] == "someOtherInfo"){ 
            echo "do other stuff";
}

I’m very new to working with PHP, so I’m sure there is something going on that I don’t understand, but I truly have no idea what could be causing these issues.

I want to get book information from GoogleBooksAPI

Assumption

I was sending a request from Nuxt.js to GoogleBooksAPI to get information about a book and suddenly I get a CORS error and cannot get the information.
This is strange because I used to be able to get it normally. I recently installed nuxt/auth to implement the login functionality and added baseURL to axios, but I don’t think those are the cause of the error. How can I get the book information from the GoogleBooksAPI?

What we want to achieve

I want to get book information from GoogleBooksAPI.

Code

export default {
  data ({ $config: { BOOK_URL } }) {
    return {
      keyword: '',
      // BOOK_URL = "https://www.googleapis.com/books/v1/volumes?q="
      BOOK_URL
    }
  },


  // URL sent to GoogleBooksAPI
  // https://www.googleapis.com/books/v1/volumes?q= "Keywords entered by the user"&maxResults=1
    get () {
      if (this.keyword.length !== 0) {
        this.$axios.get(`${this.BOOK_URL}${this.keyword}&maxResults=15`)
          .then((response) => {
            this.$store.commit('book/getBooks', response)
          })
      }
    }
  }
}

Error

Access to XMLHttpRequest at 'https://www.googleapis.com/books/v1/volumes?q=test&maxResults=15' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What we tried and what we don’t know

・ I checked the GoogleBooksAPI documentation and found no mention of any other special processing required.
https://developers.google.com/books/docs/v1/reference/volumes#resource
enter image description here

・Book information can be retrieved by accessing the URL with the error.
https://www.googleapis.com/books/v1/volumes?q=test&maxResults=15

Fast double buffered data display with simultaneous iteration for HTML5 canvas

I’m in the process of trying to optimize a game consisting of a HTML5 canvas. The basic game idea is to take an ImageData object (presumably with getImageData) and modify it, replacing the original (presumably with putImageData).
Problem is I’m concerned with the performance of getImageData followed by putImageData as the process of transferring to and from a canvas object is quite cumbersome when ideally one could just write to it directly instead. Essentiallt hoping to display a Uint8Array **while** also reading said array for the next iteration.

This is me postulating but considering how I’m *just* taking ImageData from a canvas object and using it to modify another I fail to see the need for any data to be copied as a whole ever. The data could be read from one `ImageData´, written to another after which the canvas image reference could be switched with both objects being allocated from the very beginning.

I guess what I’m after is some sort of double buffering? The idea is to modify a dataset, display it, and then use that same dataset on display for the next iteration avoiding unnecessary copying in between.