MongoServerError: E11000 duplicate key error collection: MERNSM.users index: followers_1 dup key: { followers: undefined }

MongoServerError: E11000 duplicate key error collection: MERNSM.users index: followers_1 dup key: { followers: undefined }
im confused as i dont have unique in my schema
im not sure what the problem could be as i am creating a user with unique inputs but getting this error
Register File

 export const Register = async (req,res) => {
    const user = req.body
  
    try{
        if (typeof(user.password) === "undefined" || typeof(user.username) === "undefined" ){
            res.status(205).json("Missing Details")
        }
        console.log(user)
       
        userModel.create({username:user.username,password:user.password,email:user.email})
        res.status(205).json("User Created")
    }catch(err){
        console.log("there was an error")
        res.status(405).json({messages:err.message})
    }
}

User Schema:

import Mongoose from "mongoose"

const userSchema = Mongoose.Schema({
   username:{type:String,required:true,unique:true},
   password:{type:String,required:true,},
   email:{type:String,required:true,unique:true},
   profileimg:{type:String,default:"https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"},
   Bio:{type:String ,default:""},
   following:{type:Array,default:[]},
   followers:{type:Array,default:[]}
})

const userModel = Mongoose.model("Users",userSchema)
export default userModel  aw a   a 

Element height won’t change with getBoundingClientRect()

I’m trying to resize the height of an element by using Element.getBoundingClientRect().
The height of the element was logged before and after element_box.height += 50; where the computed height does change. Yet, the height of the element doesn’t change on the page. Why does div height remain 120px when it’s suppose to be 170px?

https://jsfiddle.net/sxm2gn48/1/

<div></div>
div {
  border: 1px solid;
  height: 120px;
  width: 130px;
}
let div = document.querySelector("div");

window.addEventListener("load", function(event) {
    const element_box = div.getBoundingClientRect();
    element_box.height += 50;
})

I’m getting an error in making avatar bot in discord.js

I wanted to make a command for my bot that returns the user avatar, but I am getting an error: DiscordAPIError: Cannot send an empty message at RequestHandler.execute (C:UsersPooyanDesktopPDM Bot Mainnode_modulesdiscord.jssrcrestRequestHandler.js:350:13) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async RequestHandler.push (C:UsersPooyanDesktopPDM Bot Mainnode_modulesdiscord.jssrcrestRequestHandler.js:51:14) at async TextChannel.send (C:UsersPooyanDesktopPDM Bot Mainnode_modulesdiscord.jssrcstructuresinterfacesTextBasedChannel.js:175:15) { method: 'post', path: '/channels/885608990418010202/messages', code: 50006, httpStatus: 400, requestData: { json: { content: undefined, tts: false, nonce: undefined, embeds: undefined, components: undefined, username: undefined, avatar_url: undefined, allowed_mentions: undefined, flags: undefined, message_reference: undefined, attachments: undefined, sticker_ids: undefined }, files: [] } }

my code:

module.exports = {
    name: 'avatar',
    aliases: ['icon', 'pfp', 'profilepic'],
    permissions: [],
    cooldown: 5,
    description: '!',

    execute(message, args, client, Discord) {

        if (!message.mentions.users.size) {
            return message.channel.send(`**آواتار شما:** ${message.author.displayAvatarURL({ dynamic: true })}`);
        }

        const avatar_list = message.mentions.users.map(user => {
            return ` آواتار**<@${user.id}>** ${user.displayAvatarURL({ dynamic: true })}`;
        });

        message.channel.send(avatar_list);
    }
}

I am using Discord.js v13, node 16

return custom object by modifying the object using javascript / node js

const data = [
  {
    system: {
      id: "4gSSbjCFEorYXqrgDIP2FA",
      type: "Entry",
      content: { type: { name: "Author" } },
    },
    DataDetails: {
      shortSlugOption: { "en-us": "some value", "za-op": "random value" },
      mediaFileAssetLink: { "en-us": "some file", "za-op": "file Linl" },
      mediaFileAssetGalary: { hi: "file link 2" },
      singleMediaImage: { hi: "file link single", "en-us": "english link" },
    },
  },
  {
    system: {
      id: "1aBOO8tu3lUsjtICuIbUM5",
      type: "Entry",
      content: { type: { name: "Author" } },
    },
    DataDetails: {
      short: { "en-us": ["shorts", "values"], "za-op": "short details" },
      shortSlugOption: { "hi-In": "options" },
      booleanField: { "hi-In": "true" },
    },
  },
  {
    system: {
      id: "2pOUGnI1oRD7nsrYs600HA",
      type: "Entry",
      content: { type: { name: "testing" } },
    },
    DataDetails: { testingNewValue: { "en-us": "details value" } },
  },
  {
    system: {
      id: "66rzYr2BpWL1VTBHdLTdSW",
      type: "Entry",
      content: { type: { name: "new" } },
    },
    DataDetails: {
      oneReference: { hi: "values 1" },
      multiReference: { "hi-In": "values 2" },
    },
  },
  {
    system: {
      id: "cIb5mqEBRWDD6hrNmFmFE",
      type: "Entry",
      content: { type: { name: "new" } },
    },
    DataDetails: { testingNewValue: { "hi-IN": "jksdsdo" } },
  },
  {
    system: {
      id: "7kRzyt4PFrX13gHcw3Z1Ko",
      type: "Entry",
      content: { type: { name: "testing" } },
    },
    DataDetails: { testingNewValue: { "en-us": "kknksdo" } },
  },
  {
    system: {
      id: "2OspeCtNK0sh2cPiuU9jIz",
      type: "Entry",
      content: { type: { name: "dummy" } },
    },
    DataDetails: {
      short: { "za-op": "dfvndkssa" },
      shortSlugOption: { hi: "sdocjosmdc" },
      mediaFileAssetLink: { "en-us": "jdsojocis" },
      booleanField: { "hi-In": "true" },
    },
  },
  {
    system: {
      id: "2eAmIIuG4xkLvatkU3RUSy",
      type: "Entry",
      content: { type: { name: "dummy" } },
    },
    DataDetails: {
      dummy: { "en-us": "dshcifdvk" },
      india: { "za-op": "sdci", hi: "hewd" },
    },
  },
  {
    system: {
      id: "7hbdS3MgfZ73TOtlu1WfXw",
      type: "Entry",
      content: { type: { name: "dummy" } },
    },
    DataDetails: {
      testingNewValue: { "en-us": "sdcoklsdc" },
      locationField: { hi: "sdcndkdc" },
    },
  },
];
  result = data.reduce(
    (
      r,
      {
        system: {
          id,
          content: {
            type: { name },
          },
        },
        DataDetails,
      }
    ) => {
      r[name] ??= {};
      Object.entries(DataDetails).forEach(([key, object]) => {
        Object.entries(object).forEach(([loc, value]) => {
          r[name][loc] ??= {};
          r[name][loc][id] ??= {};
          r[name][loc][id][key] = value; 
        });
      });
      return r;
    },
    {}
  );

console.log(result)

my this is my object

fields

{
  "Author": { "fields": "shortSlugOption" },
  "testing": { "fields": "mediaaccess" },
  "dummy": { "fields": "fieldtest" },
  "new": { "fields": "fieldtest" },
}

I am trying to check and assign the value which is present inside the fields object with the key which is present in side result obj and assign the value

so in the fields object

"new": { "fields": "oneReference" }

I want to check the oneReference present in new

  "new": {
    "hi": {
      "66rzYr2BpWL1VTBHdLTdSW": {
        "oneReference": "values 1",
        "media": {
          "conf": {
            "type": "media",
            "id": "01"
          }
        }
      }
    },
    "hi-In": {
      "66rzYr2BpWL1VTBHdLTdSW": {
        "multiReference": "values 2"
      }
    },
    "hi-IN": {
      "cIb5mqEBRWDD6hrNmFmFE": {
        "testingNewValue": "jksdsdo"
      }
    }
  },

so here my expected output is like this

  "new": {
    "hi": {
      "66rzYr2BpWL1VTBHdLTdSW": {
        "subject": "values 1"
        "id": "66rzYr2BpWL1VTBHdLTdSW",
        "address": "/new/values 1"
        "oneReference": "values 1",
        "media": {
          "conf": {
            "type": "media",
            "id": "01"
          }
        }
      }
    },
    "hi-In": {
      "66rzYr2BpWL1VTBHdLTdSW": {
        "subject": "values 1"
        "id": "66rzYr2BpWL1VTBHdLTdSW",
        "address": "/new/values 1"
        "multiReference": "values 2"
      }
    },
    "hi-IN": {
      "cIb5mqEBRWDD6hrNmFmFE": {
        "subject": "unknown"
        "id": "cIb5mqEBRWDD6hrNmFmFE",
        "address": "/new/unknown"
        "testingNewValue": "jksdsdo"
      }
    }
  },

here we can see new:hi and new:hi-In contain same id 66rzYr2BpWL1VTBHdLTdSW so its should check field object oneReference present in which id and assign that value in subject but in the new:hi-IN the id cIb5mqEBRWDD6hrNmFmFE does not contain oneReference then it should print unknown like this I want to check for Author testing dummy and many more if they are present in the fields object and check the value present or not in the result and display Unknown if the value is not present but display the actual key value

so I tried this but no help

let field = {
  Author: { fields: "shortSlugOption" },
  testing: { fields: "mediaaccess" },
  dummy: { fields: "fieldtest" },
  new: { fields: "fieldtest" },
};

const data = [
  {
    system: {
      id: "4gSSbjCFEorYXqrgDIP2FA",
      type: "Entry",
      content: { type: { name: "Author" } },
    },
    DataDetails: {
      shortSlugOption: { "en-us": "some value", "za-op": "random value" },
      mediaFileAssetLink: { "en-us": "some file", "za-op": "file Linl" },
      mediaFileAssetGalary: { hi: "file link 2" },
      singleMediaImage: { hi: "file link single", "en-us": "english link" },
    },
  },
  {
    system: {
      id: "1aBOO8tu3lUsjtICuIbUM5",
      type: "Entry",
      content: { type: { name: "Author" } },
    },
    DataDetails: {
      short: { "en-us": ["shorts", "values"], "za-op": "short details" },
      shortSlugOption: { "hi-In": "options" },
      booleanField: { "hi-In": "true" },
    },
  },
  {
    system: {
      id: "2pOUGnI1oRD7nsrYs600HA",
      type: "Entry",
      content: { type: { name: "testing" } },
    },
    DataDetails: { testingNewValue: { "en-us": "details value" } },
  },
  {
    system: {
      id: "66rzYr2BpWL1VTBHdLTdSW",
      type: "Entry",
      content: { type: { name: "new" } },
    },
    DataDetails: {
      oneReference: { hi: "values 1" },
      multiReference: { "hi-In": "values 2" },
    },
  },
  {
    system: {
      id: "cIb5mqEBRWDD6hrNmFmFE",
      type: "Entry",
      content: { type: { name: "new" } },
    },
    DataDetails: { testingNewValue: { "hi-IN": "jksdsdo" } },
  },
  {
    system: {
      id: "7kRzyt4PFrX13gHcw3Z1Ko",
      type: "Entry",
      content: { type: { name: "testing" } },
    },
    DataDetails: { testingNewValue: { "en-us": "kknksdo" } },
  },
  {
    system: {
      id: "2OspeCtNK0sh2cPiuU9jIz",
      type: "Entry",
      content: { type: { name: "dummy" } },
    },
    DataDetails: {
      short: { "za-op": "dfvndkssa" },
      shortSlugOption: { hi: "sdocjosmdc" },
      mediaFileAssetLink: { "en-us": "jdsojocis" },
      booleanField: { "hi-In": "true" },
    },
  },
  {
    system: {
      id: "2eAmIIuG4xkLvatkU3RUSy",
      type: "Entry",
      content: { type: { name: "dummy" } },
    },
    DataDetails: {
      dummy: { "en-us": "dshcifdvk" },
      india: { "za-op": "sdci", hi: "hewd" },
    },
  },
  {
    system: {
      id: "7hbdS3MgfZ73TOtlu1WfXw",
      type: "Entry",
      content: { type: { name: "dummy" } },
    },
    DataDetails: {
      testingNewValue: { "en-us": "sdcoklsdc" },
      locationField: { hi: "sdcndkdc" },
    },
  },
];

Object.keys(field).map((type) => {
  const searchKey = field[type]?.fields;

  result = data.reduce(
    (
      r,
      {
        system: {
          id,
          content: {
            type: { name },
          },
        },
        DataDetails,
      }
    ) => {
      r[name] ??= {};
      Object.entries(DataDetails).forEach(([key, object]) => {
        Object.entries(object).forEach(([loc, value]) => {
          r[name][loc] ??= {};
          r[name][loc][id] ??= {};
          r[name][loc][id][key] = value;
          
        });
      });
      console.log(r);
      return r;
    },
    {}
  );
  
  const typeObject = result[type] ?? {};
  let subject;
  outer: for (key in typeObject) {
    const value = typeObject[key];
    subject = null;
    for (subkey in value) {
      const subvalue = value[subkey];
      subject = subvalue[searchKey];
      if (subject != null) break;
    }
    console.log(subject ?? "Unknown");
  }
});

How to get all the possible combinations of the empty rectangles

Preview

I have an interactive SVG space should be dynamically sliced into rectangles, the user can select any combination as example the user can select:

  1. <rect x="0" y="400" width="400" height="400" />
  2. <rect x="0" y="400" width="600" height="400" />
  3. <rect x="0" y="400" width="800" height="400" />
  4. <rect x="400" y="400" width="200" height="400" />
  5. <rect x="400" y="400" width="400" height="400" />
  6. <rect x="600" y="400" width="200" height="400" />

Those are all the possible combination for the bottom big area/rectangle
and i started with this data object:

const db = {
    room: {
        width: 800,
        height: 800,
    },
    layouts: [
        {
            x: 0,
            y: 0,
            width: 400,
            height: 400,
        },
        {
            x: 400,
            y: 0,
            width: 200,
            height: 200,
        },
    ],
};

I wanna calculate all the possible combinations of the empty (gray) rectangles given a list of the current populated rectangles.

I tried to loop through the current rectangles horizontally and vertically and subtract the area form room width and height to get the empty space but it doesn’t take into consideration the other populated rects and i have no clue how to get the combinations of the possible rects.

javascript only-click image to open link

I’m going off a template that searches the page and displays various containers. Most of the work is in the script.js file. What I want to do I click on each image in the various containers and each one will go to a different local html page. I have seen examples where you can click on an image but they seem to refer to the html page and I want this to be on the javascript part only (if possible), because I have nothing in my html to work with.

My html page is very simple. Here is the body:

<div class="wrapper">
        <div id="search-container">
            <input
              type="search"
              id="search-input"
              placeholder="Search plug-in name here.."
            />
            <button id="search">Search</button>
        </div>
        <div id="buttons">
            <button class="button-value" onclick="filterProduct('all')">All</button>
            ......
        </div>
        <div id="products"></div>
</div>

As for the javascript part, that is the bulk of what happens. I mainly know html and css, so I don’t understand everything in this part.

    let products = {
      data: [
        {
          productName: "ADSR Sample Manager",
          category: "Software",
          image: "sm_img/ADSR_Sample_Manager-260x390-01.jpg",
          link: "plug-ins/adsr-sample-manager.html",
        },
        {
          productName: "Beige Short Skirt",
          category: "Bottomwear",
          image: "short-skirt.jpg",
        },
        ......
      ],
    };

    for (let i of products.data) {
      //Create Card
      let card = document.createElement("div");
      //Card should have category and should stay hidden initially
      card.classList.add("card", i.category, "hide");
      //image div
      let imgContainer = document.createElement("div");
      imgContainer.classList.add("image-container");
      //img tag
      let image = document.createElement("img");
      image.setAttribute("src", i.image);
      
      // THIS FUNCTION opens _blank.
      image.addEventListener("click", function() {
        console.log("clicked");
        window.open(products.data.link, '_blank');
      });

      imgContainer.appendChild(image);
      card.appendChild(imgContainer);
      //container
      let container = document.createElement("div");
      container.classList.add("container");
      //product name
      let name = document.createElement("h5");
      name.classList.add("product-name");
      name.innerText = i.productName.toUpperCase();
      container.appendChild(name);

      //link IS THIS CORRECT?
      let link = document.createElement("div");
      container.appendChild(link);

      card.appendChild(container);
      document.getElementById("products").appendChild(card);
    }

    //Initially display all products
    window.onload = () => {
      filterProduct("all");
    };

Is the link part setup correctly? and the function() doesn’t work, it opens _blank, not “plug-ins/adsr-sample-manager.html”

Since I don’t know javascript very well, I’m sorry if my terms are all mixed up.

How to Update HTML using Node JS from MYSQL

Question

How can i change my HTML data in the files via node JS i am not using EJS or any view engine I have a views folders where all the files are .js files returning HTML how can i change the data from the node server which selects the MYSQL data for example if i have

I have tried using res.send but it changes the whole file how can i change for example on the about page /aboutus

<h1 id='name'></h1>

How can i add data from the server to edit that file?
thanks

How can i make Discord.js Image scraper to send new image everytime

I have been messing around with image scraper (discord.js v13).
I would love to make it so everytime i do for example ?image car it sends different picture of car.

This is my code rn, its just basic plain scraper


const google = new Scraper({
    puppeteer: {
      headless: true,
    },
  });

module.exports = {
    name: 'image',
    description: 'Send picture (possibly automatically maybe)',
    async execute( kaoru, message, args, Discord){
        const image_query = args.join(' ');
        if(!image_query) return message.channel.send('> **Please enter name of the image!**');

        const image_results = await google.scrape(image_query, 50);
        message.channel.send(image_results[0].url)
        

    }
}```


Any ideas?

I tried to google help, but didnt find anything. Also i think it has something to do with this part: ```message.channel.send(image_results[0].url)``` Because if i change [0] to [2] for example, it changes that pic. But it would be cool if it would send pics between 0-100 

Updating useReducer state from another function – React Pagination

I’m making a movie and I want to add pagination in the MoviesFromGenre component. Initially, MoviesFromGenre gets rendered based on the id from GenresList.
I want to add Pagination but I don’t know how to update the state in useReducer when I click next/prev buttons?

import React, { useEffect, useReducer, useState } from 'react';
import { useParams } from 'react-router-dom'
import axios from 'axios';
import { API_URL, API_KEY } from '../api/config.js';
import Movies from './Movies'

const initialState = {
  loading: true,
  error: '',
  movies: []
};

const reducer = (state, action ) => {
  switch(action.type) {
    case 'FETCH_SUCCESS':
      return {
        loading: false,
        movies: action.payload,
        error: '',
      };
    case 'FETCH_ERROR':
      return {
        loading: false,
        movies: [],
        error: 'Error'
      };
    default:
      return state;
  }
};


function MoviesFromGenre () {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { id } = useParams();
  const [pageNumber, setPageNumber] = useState(1)
  useEffect(() => {
    axios
      .get(
        `${API_URL}discover/movie?api_key=${API_KEY}&language=en-US&with_genres=${id}`
      )
      .then(response => {
        dispatch({
          type: 'FETCH_SUCCESS',
          payload: response.data
        })
      })
      .catch(err => {
        dispatch({
          type: 'FETCH_ERROR'
        })
      })
  }, [])

  const nextPage = () => {
    axios
      .get(
        `${API_URL}discover/movie?api_key=${API_KEY}&language=en-US&with_genres=${id}&page=${pageNumber}`
      )
      .then(response => {
        console.log(response.data)
      })
    setPageNumber(pageNumber+1)
  }

  const prevPage = () => {
    axios
      .get(
        `${API_URL}discover/movie?api_key=${API_KEY}&language=en-US&with_genres=${id}&page=${pageNumber}`
      )
      .then(response => {
        console.log(response.data)
      })
    setPageNumber(pageNumber-1)
  }

  return (
    <div>
      <Movies state={state}/>
      <button onClick={prevPage}>Prev</button>
      <button onClick={nextPage}>Next</button>
    </div>
  )
}

export default MoviesFromGenre;

I created a repository on GitHub.

I want to update the movies state when I click on next or prev buttons.

How to save and load drawings from a database?

As far as I know I am supposed to save it to a GeoJSON file.
I am using Openlayers 6 and my setup looks like this:

window.onload = init;

//draw on the map interaction

    const drawInteraction = new ol.interaction.Draw({
        type: 'Circle',
        freehand: true
    })
    map.addInteraction(drawInteraction);

    drawInteraction.on('drawstart', function(e){
        console.log("Drawing Started")
    })
    
    drawInteraction.on('drawend', function(e){
        let parser = new ol.format.GeoJSON();
        let drawnFeatures = parser.writeFeaturesObject([e.feature]);
        console.log(drawnFeatures.features[0].geometry.coordinates) // logs only the coordinate
        console.log("Drawing Finished")
    })

}

I am new to this and am struggling figuring out how to save and load the drawings that I do on the map.

I use is mysql with Wampserver.

how to import file from “src” folder to “public” folder in JavaScript?

I’m trying to create SPAPWA using Vue Js.

I want to import a file of functions to public folder from src folder.

enter image description here

so i do this:

index.html file in public folder:

enter image description here

in the first time i get this err: Uncaught SyntaxError: Cannot use import statement outside a module then I added type="module" but now i get this err: GET http://localhost:8080/src/scripts/sc.js net::ERR_ABORTED 404 (Not Found)

how can i fix that?

React html date picker change date label

enter image description here

When I capture the selected date to a variable it displays like this “YYYY-MM-DD”
But in the HTML date picker “MM/DD/YYYY”

All I want is to change that label to “YYYY-MM-DD” from “MM/DD/YYYY”. I hope there should be a way to do this in JS with React instead of using another date picker library. How do I do this in React?

Codesandbox

Get the firsts json items with axios

I’m working on the front-end of an API in react and I’m trying to get the ten first items of a JSON list like:
[{"element1":"value", "element2":"value"}, {"element1":"other value", "element2":"other value"}, ...]
But I don’t know how to do that with Axios :/
I found nothing in the Axios’ Docs or on this forum

Thanks for your help 🙂

JavaScript Problems 0001

How do I get an undefined error while using JS dataset to try to get data from a Django template cant fix it, can anyone provide a solution? The index.html template

How can I solve this problem?