How to Count Number of Data in MongoDB and Display to EJS

I get an output when I’m displaying it through console log, but when I try to display it through ejs I get no output. Is there any way I can display my .countDocument() result through ejs?

Here’s my code:

const getDocument = async() => {
try{
    const result = await Contact
    //to count only the services 
    .find({$or: [{subject:"Land Surveying"} , {subject:"Construction"} , {subject:"Consultation and Planning"} , {subject: "Architecture"}]})
    .countDocuments();
    console.log(result);
}catch(err){
    console.log(err);
}

}
getDocument();

React uncheck input type check on specific condition

I have 3 inputs type check fields

  • input pick man
  • input pick woman
  • input pick special

The user shall only be able to check a man or woman + special.

The user shall not be able to pick man and woman.

If the users pick man first and wants to pick woman afterwards, the man input shall be unchecked and the woman checkbox shall be picked / checked.

Basically I have following conditions:

  • man + special – allowed
  • woman + special – allowed
  • man + woman – not allowed (only one of them can be picked)

How can I implement this?

So far I have done this:


const TargetViewCard = ({ onChangeTraits }: Props) => {
  const { targetGroupData, targetGroupIsLoading, targetGroupIsError } = useTargetGroupData()
  const [selectedTarget, setSelectedTarget] = useState<ITargetItem[]>([])

  const findTarget = (id: string) => targetGroupData.items.find((target: ITargetItem) => target.id === parseInt(id))

  const checked = (item: ITargetItem) => !!selectedTarget?.find(c => c.id === item.id)

  const toggleTarget = (e: ChangeEvent<HTMLInputElement>) => {
    const target = findTarget(e.target.value)

    let sTarget
    if (selectedTarget.includes(target)) {
      sTarget = selectedTarget.filter(selectedTarget => selectedTarget.id !== target.id)
      setSelectedTarget(selectedTarget.filter(selectedTarget => selectedTarget.id !== target.id))
    } else {
      sTarget = [...selectedTarget, target]
      setSelectedTarget([...selectedTarget, target])
    }

    onChangeTraits(sTarget)
  }

render(
    ...
    {targetGroupData.items.map((item: ITargetItem) => (
        <div key={item.name} className="py-4">
            <label htmlFor={`target-item-${item.id}`}>
            <div>
                {item.name}
                <input
                id={`target-item-${item.id}`}
                name={`target-item-${item.id}`}
                type="checkbox"
                className="hidden"
                value={item.id}
                onChange={e => toggleTarget(e)}
                />
            </div>
            </label>
        </div>
    ))}
)

How to display radio and checkbox values in table using javascript?

form.html

<div class="container">
  <br>
<br>
  <h3 class="text-center">Display answers of form fill in inside a table</h3>
  <br>
<br>
  <form>
  <div class="form-group">
    <label>First Name</label>
    <input id="name" class="form-control form-control-sm" />
  </div>

<div class="form-group">
    <label>Age</label>
    <input id="age" class="form-control form-control-sm" />
  </div>
   
   <div class="form-group">
    Gender:<input type="radio" name="male" id="gender" value="male">Male
       
        <input type="radio" name="female" id="gender" value="female">
        <label for="female">Female</label>
  </div>
    
 <div class="form-group">
<label>Language</label>
  <input type="checkbox" id="language" name="malayalam" value="Malayalam">Malayalam
        <input type="checkbox" id="language" name="english" value="English">English
        <input type="checkbox" id="language" name="hindi" value="Hindi">Hindi
 </div>
  <button type="button" id ="display" class="btn btn-sm btn-primary">Display</button>
</form>


<br>
  <br>
<table  class="table border" id= "table" >
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Language</th>
</tr>
</table>

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

form.js****

(function setup() {
“use strict”;

var NameElem = document.getElementById("name");
var genderElem = document.getElementById("gender");
var ageElem = document.getElementById("age");
var languageElem = document.getElementById("language");
var tableElem = document.getElementById("table");
document.getElementById("display").addEventListener("click", function () {
    var newRow = tableElem.insertRow(-1);
    var newCell = newRow.insertCell(0);
    var newText = document.createTextNode(NameElem.value);
    newCell.appendChild(newText);
    newCell = newRow.insertCell(1);
    newText  = document.createTextNode(genderElem.value);
    newCell.appendChild(newText);
    newCell = newRow.insertCell(2);
    newText  = document.createTextNode(ageElem.value);
    newCell.appendChild(newText);
    newCell = newRow.insertCell(3);
    newText  = document.createTextNode(languageElem.value);
    [newCell.appendChild][1](newText);
    NameElem.value = "";
    genderElem.value = "";
    ageElem.value = "";
    languageElem.value = "";
    tableElem.value = "";
});

})();

When i click display button it displays name and age but gender and checkbox is incorrect it displays first value only. I want to display which i select.
radio data and checkbox data should display
I have given image also please check

How to offset matrix values from up to down by row in Javasript?

I have a matrix and a flip_value that goes for the first element, I want to offset or push down the numbers of a selected column.
For example

let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],

];

I want to change the matrix-like that:
So in the second (1st row in the program) is pushed down by 1 and the first element changed.

flip_value  = 999
let matrix =  [1, 999, 3, 4],
        [5, 2, 7, 8],
        [9, 6, 11, 12],
        [13, 10, 15, 16],

The new flip value is 14.

Could you also give me a hint on how to do this from down to up?
flip_value = 999
Like that:

let matrix = [
    [1, 6, 3, 4],
    [5, 10, 7, 8],
    [9, 14, 11, 12],
    [13, 999, 15, 16],

];

//In this method the second-row values are pushed down to up by 1 and the last value in second row the last element flipped.
The new flip_value = 2 here

The whole code which is not working

let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],

];

let Yindex = 1;
let flip_value = 999;
let size = 4;




let flip_tmp = matrix[size - 1][Yindex];
console.log("fontos");
for (let i = 1; i < size; i++) {
    //  matrix[i][Yindex] = matrix[i-1][Yindex];
    let tmp = matrix[i][Yindex];
    matrix[i][Yindex] = matrix[i - 1][Yindex];
    matrix[i - 1][Yindex] = tmp;

    console.log(matrix[i][Yindex] + "=" + matrix[i - 1][Yindex]);
}


matrix[0][Yindex] = flip_value;
flip_value = flip_tmp;
for (let i = 0; i < size; i++) {
    console.log("n");
    for (let j = 0; j < size; j++) {
        console.log(matrix[i][j] + " ");
    }
}

for (let i = 0; i < size; i++) {
    console.log("n");
    for (let j = 0; j < size; j++) {
        if (j == 1) {
            console.log(i + "" + j + " " + matrix[i][j] + " ");
        }

    }
}

How to validate phone number in react that until user give valid phone number button should disabled

import React,{useState} from "react";
export default function Validate() {
  const [value, setValue] = useState("");
  const [disable, setDisable] = useState(false);
  function handleChange(e) {
    setValue(e.target.value);
    if (e.target.value.length <10)
     {
      setDisable(true);
    }
  }
  return (
    <>
      Phn:<input error={disable} type="number" value={value} onChange={handleChange}/>
      <button disabled={!disable}>click</button> 
    </>
  );
}

in this case initially button is disabled but when i type one number button is enabled but i need untill user give 10 digit phone number button is disabled

How can I save mongoose data? It doesn’t work


var userid 


User.find({ name: "송형준" }).then(result =>{
    result.forEach(result => {
        userid = result._id
    })
});

const create_room = new Room({
    room_name: 'sexy',
    user_list: `${userid}`,
})

create_room.save()

I’ve been trying to run this code.
But it doesn’t work.
I think the ploblem is in the grammar

Updating component state inside array.map() causing too many re-renders

import useState from "react-usestateref";

const [meta, setMeta, metaRef] = useState({});

Inside component’s JSX:

data.result.map((token) => {
                        const id = token.token_id;
                        const params = { uri: token.token_uri };

                        if (token.metadata) {
                            setMeta(JSON.parse(token.metadata));
                        } else {
                            Moralis.Cloud.run("get_token_uri", params).then(
                                (response) => setMeta(response)
                            );
                        }
                        const { name, description, imageUrl } = metaRef.current;
                        return (
                            <Card
                                key={id}
                                tokenId={id}
                                name={name}
                                description={description}
                                user_address={user_address}
                                imageUrl={fixURL(imageUrl)}
                                calledFrom={calledFrom}
                            />
                        );
                    })

I want to update the meta state variable from inside data.result.map and use the updated meta object to return a Card component. I’m using react-usestateref to get the current value of the meta state variable. Otherwise, meta still remains {} when de-structuring, even after being updated. If token.metadata is not null I want to set the meta state var to token.metadata obj and if it is null, I want to make an asynchronous request to get back the object from Moralis and then set it to the meta state var. This code is producing the following error: Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

How can I make this code work as intended?

Why can’t the posts made by the user be displayed?

In the backend I can use my Token to search after Notes which User creates.
In my Frontend project it doesn´t show me my Posts ..

I store my token in localStorage “userInfo” .. so it can be taken from there if I login to my account.

my NotesSchema :

const forumSchema = ({
    forumName: {
        type: String,
        required: true,
    },
    forumDescription: {
        type: String,
        required: true,
    },
    createdBy: { 
        type: Schema.Types.ObjectId, ref: 'User' 
    },
    published_on: {
        type: String,
        default: moment().format("LLL")
    },
});

My note route :

router.get('/getByOwnerID',verifyToken,ForumService.getByToken);

And the function which I wrote for that :

exports.getByToken = async (req, res, next) => {
  Forum.find({ userID: req.token.userID }) 
  .then(doc => {
      if(!doc) { return res.status(400).end();}
      return res.status(200).json(doc);
  })
  .catch(err => next(err));
}

And the frontend noteAction.js:

export const listNotes = () => async (dispatch, getState) => {
    try{
        dispatch({
            type: NOTES_LIST_REQUEST,
        });
        const {
            userLogin: { userInfo },
        } = getState();

        const config = {
            headers: {
                Authorization: `Bearer ${userInfo.token}`,
            },
        };

        const { data } = await axios.get(`http://localhost:8080/forum/getByOwnerID`, config);
        
        dispatch({
            type: NOTES_LIST_SUCCESS,
            payload: data,

        });
        }catch(error){
            const message = 
                error.response && error.response.data.message
                    ? error.response.data.message
                    : error.message;
            dispatch({
                type: NOTES_LIST_FAIL,
                payload: message,
            });
        }
    }

I hope it´s clear if not I can add Information ..

Phaser-3: Is there a way to move an image from one location to another while the program is running and so it is visible doing so?

i would like to create a battle system for an rpg game ,where an opening animation plays showing the battling characters move from the side of the screen to a location on the screen. Current code, assets and current running view provided below;

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>battle</title>
    <script src="phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>


<script type="text/javascript">
var config = {
    type: Phaser.AUTO,
    width: 1900,
    height: 900,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 0},
            debug: false
        }
    },
    scene: {
        preload: preload,
        create: create,
        update: update,
        
        }
    };
var game = new Phaser.Game(config);

function preload(){ 
    this.load.image("background","assets/battle background.png");
    this.load.image("hydroBot","assets/water hydrant.png");
    
};
function create(){
    const battle = this.add.image(0,0,"background").setOrigin(0,0);
    const bot= this.add.image(1000,200,"hydroBot");
    bot.setScale(5);
   
    
};
function update(){

};

</script>
</body> 

water_hydrant/hydrobot

the battle background

the current view when running the code

much appreciated thanks 🙂

How to use XPath in a newly opened window?

With the code below, I am trying to open a new window, look for certain span-elements, and click each of them. However, I cannot access the code of the new window through XPath.

  • Inserting the code (copy & paste) of the clickElem function directly in the new tab works fine
  • CORS shouldn’t be a problem since it’s the same domain
  • I’ve been also following this answer.

JavaScript:

const w = window.open('https://example.com', 'Example', 'width=500, height=500');
w.clickElem = () => {
    const xpath = '//span[text()="Click here"]';
    const selectedNodeElements = w.document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
    let currentNode = selectedNodeElements.iterateNext();
    while (currentNode) {
        currentNode.click();
        currentNode = selectedNodeElements.iterateNext();
    }
}
setTimeout(w.clickElem, 8000);

When I try to access the text via currentNode.textContent I receive following error:

"Error in protected function: Cannot read properties of null (reading 'textContent')"

Grateful for every hint!

Cannot access ‘usagePrice’ before initialization

I have a script that I’m using to calculate the price of a selected field

When i run the function ‘calculateTotal()’ i get this error “Cannot access ‘usagePrice’ before initialization”.

Here is my code:

// Returns total for step 1
const usagePrice = () => {
    const field = document.querySelector('input[name="usage"]:checked');
    const subField = document.querySelector('input[name="varifocal-lenses"]:checked');

    let price = field.dataset.price;
       

    if (field.value == 'varifocal') {
        
        price = subField.dataset.price;
    }

    console.log('Usage price: ' + price);
    return price;
}

// Adds all totals together
const calculateTotal = () => {
    const usagePrice = usagePrice();
    const prescriptionPrice = prescriptionPrice();
    const lensPackagePrice = lensPackagePrice();
    const lensTypePrice = lensTypePrice();

    const total = usagePrice + prescriptionPrice + lensPackagePrice + lensTypePrice;

    return total;
}


console.log(calculateTotal());

Can anyone explain whats going wrong? Thank you in advance.

How can I set data createContext?

HOW CAN I SET DATA INTO THE STATE?

** And how can i solve createContext error? **

export const LastChanceContext = createContext() //in there return error: Expected 1 arguments, but got 0.

export const GET_LASTCHANCE = “GET_LASTCHANCE”

const LastChanceWrapper = ({children} : {children:any}) => {

const initialState = {
    lastChances: [],
    lastChance: {}
};
console.log('asd',initialState);

const [state, dispatch] = useReducer(lastChanceReducer, initialState);

useEffect(() => {
    const getLastChance = async () => {
        const result = await axiosFetch('http://65.21.148.176:2803/api/Home/Get');
        const action = {
            type:GET_LASTCHANCE,
            payload:result.data.data.lastChanceList
        };
        if(Object.keys(result).length !== 0) {
             dispatch(
                 {state,
                action}
             )

            console.log(result.data.data.lastChanceList);
        }

    };

    getLastChance();
}, [])


return (
    <LastChanceContext.Provider value={{
        lastChances: state.lastChances,
        lastChance: state.lastChance
    }}>
        {children}
    </LastChanceContext.Provider>
)

}

export default LastChanceWrapper