use mongodb data with mongoose on google map API on node js

Hello and Welcome to my question!

I want to make a fairly simple website

I have some data in my database and I want to use them on a google maps API
Basically, I want for each place that I have stored, in my db, to have a marker at it’s coordinates

My mongoose schema is this:

const mongoose = require('mongoose')

const placeSchema = new mongoose.Schema({
    _id: String ,
    name: String,
    address: String,
    types:[ String ],
    coordinates:{ lat: Number, lng: Number },
    rating: Number,
    rating_n:Number,
    current_popularity: Number ,
    populartimes:[
        {
            name: String ,
            data: [ Number ]
        }
    ],
    times_spent: [ Number ]
})

module.exports = mongoose.model('place', placeSchema)

I have read the google API docs and I am trying to do it as they say but I cannot get my data in my js file that my function initMap() is in.

The path is like this:
/login/user

And the user.ejs file is:

<script type="text/javascript" src="js/user.js"></script>

<div class="container">
<div class="form-uheader">
    <h1>Welcome <%if (typeof user != 'undefined'){%> 
        <%= user.username %> 
        !
    <% } %> </h1>
        <h2>Let's evaluate your choices.</h2>
</div>
</div>
<div class="container">
    <div class="dropdown">
        <button onclick="openDropdown('map')" class="drop_btn"><img src="images/map.png" alt="#"><h1>What is next to you?</h1></button>
        <button onclick="openDropdown('search')" class="drop_btn"><img src="images/search.png" alt="#"><h1>Points of Interest</h1></button>
        <button onclick="openDropdown('verify')" class="drop_btn"><img src="images/verify.png" alt="#"><h1>Register a Visit</h1></button>
        <button onclick="openDropdown('nervous')" class="drop_btn"><img src="images/nervous.png" alt="#"><h1>Possible contact with a covid case</h1></button>
        <button onclick="openDropdown('patient')" class="drop_btn"><img src="images/patient.png" alt="#"><h1>Do you have Covid?</h1></button>
        <button onclick="openDropdown('edit')" class="drop_btn"><img src="images/edit.png" alt="#"><h1>Edit your profile</h1></button>
    </div>
    <div id = "data">
        <% if(typeof place != 'undefined'){ %> 
            <%var places = place %>
        <% } %> 
    </div>
</div>   

<div class="container">        
    <div id="menu" class="dropdown-menu">
        <div class="dropdown-item" id = "item-map">
            <div id="map"></div>
            <% //script for maps API %> 
            <script
              src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAPmkodwFVGpcTcpFyUbeDxaAwYYlUJjnM&callback=initMap&v=weekly"
              async
            ></script>
            <script src="js/map.js"></script>
            <% //END script for maps API %>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-search">
            <div id = 'search'>
                search
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-verify">
            <div id = 'verify'>
                verify
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-nervous">
            <div id = 'nervous'>
                nervous
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-patient">
            <div id = 'patient'>
                patient
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
        <div class="dropdown-item" id = "item-edit">
            <div id = 'edit'>
                edit
            </div>
            <span class="closebtn" onclick="this.parentElement.parentElement.style.display='none';">&times;</span>
        </div>
    </div>
</div>

Basically, there are 6 buttons and when 1 of them is pressed a different dropdown menu appears.

I have tried to pass my data to user.ejs, but I could not use my variable between tags
I cannot connect to mongo schema in static js file (As it was expexted)

Lastly I will present you my login route:

const express = require('express')
const router = express.Router()
const User = require('../models/user')
const Place = require('../models/place')

// Main Route
router.get('/', (req, res )=> {
    const fromReg = req.query.valid

    console.log(fromReg)
    res.render('login',{
        'page':'login',
        fromReg
    })
})

router.get('/user', (req, res) => {
    res.render('login/user',{
        'page' : 'user'
    })
})

router.get('/admin', (req, res) => {
    res.render('login/admin',{
        'page' : 'admin'
    })
})

//Create About Route
router.post('/', async (req, res) => {

    User.findOne({ email : req.body.email }).then( async (user) => {
        if(user){
            if (user.password === req.body.password) {
                if (user.admin){
                    //login admin
                    res.render('login/admin',{
                        'page' : 'admin',
                        user
                    })
                }else{          
                    const place = await Place.find({})    
                    res.render('login/user',{
                        'page' : 'user',
                        user,
                        place
                    })
                    
                }
            }else{
                const alert = [];
                alert.push({ msg: 'Email or Password is not correct'})
                res.render('login', {
                    'page' : 'login',
                    fromReg : false,
                    alert
                })
            }
        }else{
            const alert = [];
            alert.push({ msg: 'Email or Password is not correct'})
            res.render('login', {
                'page' : 'login',
                fromReg : false,
                alert
            })
        }
    })
})

module.exports = router 

And I have to tell you that I have 1 javascript file called user.js, that does the animations on the page
and 1 more that is called map.js that basically is copied and pasted from google API documentation

Just to sum up, I would like to know how (but firstly, if) I can use my data in a client-side js file (at least I think this is client-side), or else how can I achieve the end result that I want

Plus this is how my user page looks like:
enter image description here

Displaying images from array of objects fails when mapping

I’m learning ReactJS and I’m trying to display a list of socials from an array of objects just like so :

const baseUrl = "./";
export const SocialData = [
    {
        platform: "Linkedin",
        link: "https://www.linkedin.com/in//",
        icon: baseUrl + "linkedin.png",
    },
    {
        platform: "Github",
        link: "https://github.com/",
        icon: baseUrl + "github.png",
    },
];

Then in my component I would display it like this :

import { SocialData } from "../../data/social";
import "./socials.css";

function Socials() {
  const data = SocialData;
  return <div className="social-contact"> 
{/*     <img src={require('./linkedin.png')}/>
 */}  {
      data.map((item) => {
          return (
          <a href={item.link} key={item.platform}>
            <div className="social-icon-div">
              <img src={ require(item.icon) } className="social-icon" />
            </div>
          </a>
          )
      })}
    </div>;
}

The commented image works just fine, yet when I’m trying to do the same in my map it says and throw this error:

Uncaught Error: Cannot find module ‘./linkedin.png’
at webpackEmptyContext (socials|sync:2:1)
at Socials.js:14:1
at Array.map ()
at Socials (Socials.js:7:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)

I’ve tried to put the require in the data directly, it does the same.
I also tried

<img src={require( “” + props.src )} alt={props.imageAlt} />

As explained here but nothing did the job.
Thanks for your help!

Microsoft Word API – how to I from Word.RequestContext.document to Office.Document

I am starting the “Build your first Word task pane add-in” tutorial.

Basically I want to make a Button on the Panel that will send this document as a PDF to my web service.

There is a function in the API called Office.Document.getFileAsync which seem to be an excellent way to save data to a PDF, which I can then send to my web service.

How do I access that part of the API. In the tutorial it seem that we should use the context object, but context.document.getFileAsync does not appear to exist. I think I need to get to the Office.Document object and I think context.document is Word.RequestContext.document.

export async function run() {
  return Word.run(async (context) => {
    /**
     * Insert your Word code here
     */

    {{Office.Document then use getFileAsync  }}

    await context.sync();
  });
}

How to expose an Environment Variable to the front end in Next.js?

The Problem

I am trying to pass an environment variable to the front end to display a map from MapBox.

My Attempts

  1. I have place the API Key into the root of my directory:
//.env.local
MAPBOX_KEY="abc123"
  1. In the front-end, client side, I am trying to load that ENV to render a map:
// components/MapBox.js
export default function MapBox(){
  const MAPBOX_TOKEN = process.env.MAPBOX_KEY

  return (
    <MapGL mapboxApiAccessToken={MAPBOX_TOKEN} />
  )
}

The above code does not seem to recgonize the API KEY.

  1. When I console.log(process.env.MAPBOX_KEY) in this component, I can see the API Key in the terminal while i’m running yarn dev

Is there a way to load this env to the front end?

Note: I am using the react-map-gl package built on top of MapBox

Not a function TypeError when trying to split a user input inside a function

I created two functions and a global object data. I am trying to split what a person inputs inside a text area into individual strings and push them in the global object. The Error I have says userInputParam.split is not a function.

let data = {
  userInput: [],
  splittedInput: [],
  slicedInput: [],
};


function updateUserInput(data) {
  if (data.userInput.length == 0) {
    //   console.log("You can do this Panda!")
    data.userInput.push(input.value);
    //input.value is what a user inputs in a textarea. 
    splitUserInput(data.userInput)
  }
}

function splitUserInput (userInputParam){
    let splittedInput = userInputParam.split(/([*/+-])/)
    //console.log(splittedInput)
}

Problems displaying new div when onMouseOver event fires

I’ve made a CSS grid displaying a <p>{name}</p> element on each grid item. When an onMouseOver hover events I want to display a new div (contained within the react fragment), but in the same position.
Instead of using CSS, I’ve used JavaScript to code the logic for this – when a user hovers on the grid item, it flips a boolean (saved as state variable isMouseHovering) from false to true.
I have a conditional statement that displays the ‘new’ div, when this state value is truthy.

The problem is that this logic applies for grid item container element, and not for the elements inside the grid container. So when I over over grid, it does what it’s supposed to do and displays the new div. However when I hover over the p-tag within the grid item container element, it flickers between states.

How do I structure this so that the div changes on hover, no matter where on the grid item the user hovers the mouse?

Project.js

import { useState } from 'react'

const Project = ({name,url,techStack,image,blurb}) => {

  const [isMouseHovering, setMouseHovering] = useState(false);

  const handleOnMouseOver = () => setMouseHovering((isMouseHovering) => !isMouseHovering);  
  const handleMouseOut = () =>  setMouseHovering(false);
  
  return(
    <div className = 'grid-item' onMouseOver={handleOnMouseOver} onMouseOut = {handleMouseOut}>
      {
        isMouseHovering ? (
        // element I want to display when mouse hovering, in same position as <p>{name}</p> element
        <>
          <a href='https://xxxxxxxxxxxxxxxx'>
            <p>website</p>
          </a>
        </>
        )
        : 
        <p>{name}</p>
      }
    </div>
  )
}


export default Project

Mocha and Import Syntax: Cannot find module

Maintainer of multiple npm packages here. Been using mocha with the require syntax and wanting to migrate to the import syntax.

The error I am getting is

Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js

Steps to Reproduce

With the following three files

  • src/index.js
export const sum = (a, b) => a + b;
  • test/index.spec.js
import { sum } from '../src/index';

const expect = require('chai').expect;

describe('Testing Index', () => {
    it('Testing sum', () => {
        expect(sum(7, 13)).to.equal(20);
    });
});
  • package.json
{
  "name": "mocha-debug",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "mocha "./test/**/*.spec.js""
  },
  "license": "ISC",
  "devDependencies": {
    "chai": "4.3.4",
    "mocha": "9.1.4"
  }
}

and using node v14.18.2, run yarn install and

yarn test

> `Cannot find module '<project>/src/index' imported from <project>/test/index.spec.js`

Notes

I’ve found a related issue that recommends using babel with --require @babel/register, but wasn’t able to get over the error.

I’ve set up a test repo to make it easy to reproduce the issue

https://github.com/simlu/mocha-debug

Question

What am I doing wrong here? How do I get the tests to run successfully?

Is creating element and set innerHTML more efficient or add HTML directly?

Please forgive confusing question above…

I have a dashboard that will fetch json data with ajax for every couple seconds. The current solution is it will clear the dashboard, and get the json data and combine them with html, so is kind of like this:

$.ajax({
    ....
}).done((res) => {
    $mainBody.html('');
    for (let i = 0; i < res.length; i++){
        let ele = '<div class="...">  with adding the json data  </div>';
        $mainBody.append(ele);
    }
})

Each ele will contain around 55 lines of html code, and most of time will loop for more than 20 times to finish adding all elements.

And now I want to take a more object-oritented approach to this dashboard and considering to use document.createElement() for all elements, and then to set their innerHtml directly after every fetch. But I’m not so sure on efficiency wise and speed, which solution should I use.

Using a Javascript Map as data in D3

I’m trying to set the datum of svg rectangles using a js Map, but it isnt working. I think the “d.key” is wrong but not sure. I want the map key to be the data at this point.

The data:

    const music = new Map();
    music.set("2345",{str:"4",fret:"6"});
    music.set("5478",{str:"5",fret:"2"});
    music.set("4317",{str:"4",fret:"3"});
    music.set("3455",{str:"5",fret:"12"});
    localStorage.setItem("testMusic",JSON.stringify(Array.from(music.entries())));

The code (partial):

let data = new Map(JSON.parse(localStorage.testMusic));
//let data = localStorage.getItem("testMusic");
d3.select("#demo1")
.selectAll("rect")
.data(data,function(d) { return d.key})
.enter()
.append('rect')

Express route with multer middleware can’t redirect

I was working with multipart/form-data to recieve a from with pictures and I keep having a problem trying to redirect to another route, even if I not send any data to that router it never reaches it.

    app.listen(8080, () => {
        console.log('listening on port 8080');
    });
    app.use(express.json())
    app.use(express.urlencoded({ extended: true }))
    const upload = multer({ dest: 'uploads/' })

    app.get('/', upload.none(), (req, res) => {
        console.log("works here");
        console.log(req.body)
        /**
         *  [Object: null prototype] {
                email: '[email protected]',
                ocupation: 'some ocupation',
            }
        */
        // res.status(200).send("this would work")
        res.redirect('/destiny')
    })


    app.get("/destiny", upload.none(), (req, res) => {
        res.status(200).send("It never reaches here")
    })

I think it has something to do with multer returning the req.body as [Object: null prototype]?

Should I use another library? or recieve the picture separately

When i use Async/Await i get the warning of : Can’t perform a React state update on an unmounted component

I have already solved this problem, but I don’t know why it works… When I use Async/Await the error persists

const [data, setData]= useState([])
const thisComponent = useRef(true)
useEffect(async()=>{

    const http = axios()
    const {data:{restaurants}}= await http.get('/restaurants')
    if(thisComponent.current){
        setData(restaurants)
    }

    return ()=>{
        thisComponent.current=false
    }
},[])

Can iframe add parameters to URL?

What I want is to add a parameter to the URL of the parent document from a script inside the iframe that is in the webpage.
I made this code:

document.querySelector("#id").addEventListener("click", () => {

    window.history.replaceState(null, null, "?qwe=sub")

});

Why are you allowed to omit arguments from a JavaScript function?

In JavaScript, how come you are able to pass no arguments to a function that “requires” arguments?

For example:

function printName(name) {
    if (name) console.log(name);
    else console.log("No name");
}

printName();

However, if you try the same thing in Python you get an error:

def foo(name):
    if name: print(name)
    else: print("No name")

foo()
TypeError: foo() missing 1 required positional argument: 'name'

Original exception was:
Traceback (most recent call last):
  File "random.py", line 5, in <module>
    foo()
TypeError: foo() missing 1 required positional argument: 'name'

I can tell this relates to the undefined keyword: if you console.log() nothing, it logs undefined.

Can somebody explain what is going on when it does this/how this is allowed to work in relation to other languages that don’t allow it, such as Python?

How to build entire dataset prior to sending AJAX -Jquery

I have a system that allows an admin to add managers to a campaign from a table. The table looks something along the lines of

<tr>
<td>Checkbox</td>
<td>Last name, First name</td>
<td>Employee Id #</td>
</tr>

Currently, when the “Add Manager” button is hit, I pass the manager’s id and a “checked” value using this function

<script>
    function addMgrs(){
        dict = {}
        $('#potentialReviewers tr').each(function() {
            var userPid = $(this).find('td').eq(2).text()
            var addMgrBox = $(this).find('.addMgrBox').attr('value')
            if (addMgrBox == 'checked') {
                dict[userPid] = addMgrBox }
        // Create the Post request, pass the csrf_token in the header of the request
        $.ajax({
                url: '/campaign-view/' + '{{ campaign.id }}' + "/",
                type: 'POST',
                headers: {'X-CSRFtoken': '{{ csrf_token }}'},
                data: dict,
                dataType: 'json'
            })
        })
    }
</script>

What this does is iterate through the table, build the JSON response and pass it back to the Django view to do the backend processing. My problem is this, for each row it sends a POST request and that drastically increases the time it takes for the process to complete. I’d like it to build the entire dictionary prior to sending the response, but just can’t wrap my head around how to do that. Any help would be appreciated.