0

how can i convert this working mongoose code to a working MYSQL code?, i have a project where i fetch data from online api that updates every 24hours auto, and i need to insert that data information to database mysql but im new to mysql. im using react and node for my project.

import fetch from 'node-fetch';
import mongoose, { mongo } from 'mongoose';

mongoose.connect("mongodb://127.0.0.1:27017/highscore");

const postSchema = new mongoose.Schema({

    position: {
        type: Number,
        required: true
    },
    id: {
        type: Number,
        required: true
    },
    score: {
        type: Number,
        required: true
    },

});

const Post = mongoose.model('Players', postSchema);

async function getPosts() {
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
    const response = await getPlayers.json();
    for( let i = 0;i < response.players.length; i++){

const post = new Post({
    position: response.players[i]['position'],
    id: response.players[i]['id'],
    score: response.players[i]['score'],
});
post.save();


    }

}
getPosts();

SOME backend code i put together but have no idea where to add the api

app.post('/create', (req, res) => {
    const position = req.body.position
    const name = req.body.name
    const alliance = req.body.alliance
    const points = req.body.points

    db.query("INSERT INTO stats (position, name, alliance, points) VALUES (?,?,?,?)",
        [position, name, alliance, points],
        (err, result) => {
            if (err) {
                console.log(err)
            } else {
                res.send("Values Inserted")
            }

        }
    );

});

*** COMPLETE CODE THAT FETCHES DATA FROM API ***

const Table = () => {
  const [playerName, setPlayerName] = useState([]);
  const [playerRank, setPlayerRank] = useState([]);
  const [player, setPlayer] = useState([]);
  const [perPage, setPerPage] = useState(10);
  const [size, setSize] = useState(perPage);
  const [current, setCurrent] = useState(1);
  const [players, setPlayers] = useState();

  const fetchData = () => {
    const playerAPI = 'http://localhost:3008/api/players';
    const playerRank = 'http://localhost:3008/api/highscore/players';

    const getINFOPlayer = axios.get(playerAPI)
    const getPlayerRank = axios.get(playerRank)
    axios.all([getINFOPlayer, getPlayerRank]).then(
      axios.spread((...allData) => {
        const allDataPlayer = allData[0].data.players
        const getINFOPlayerRank = allData[1].data.players
        const newPlayer = allDataPlayer.map(name => {
          const pr = getINFOPlayerRank.find(rank => name.id === rank.id)


          return {
            id: name.id,
            name: name.name,
            status: name.status,
            alliance: name.alliance,
            position: pr?.position,
            score: pr?.score
          }
        })

        setPlayerName(allDataPlayer)
        setPlayerRank(getINFOPlayerRank)

        console.log(getINFOPlayerRank)
        console.log(newPlayer)
        setPlayer(newPlayer)
      })
    )
  }
  useEffect(() => {
    fetchData()
  }, [])
  • I don't see `react` at all ... – KcH Nov 04 '22 at 05:58
  • i just posted the code that fetches the data information – yandry santana Nov 04 '22 at 06:01
  • its a backend/frontend project, i fetch the data from API and insert it into a table that displays in the website, but now i need to insert that data into mysql table. i know how to do it on Mongoose but im new to mysql – yandry santana Nov 04 '22 at 06:02
  • I guess you should be searching for [Node-MySQL tutorial](https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp) something like that ... – KcH Nov 04 '22 at 06:06
  • yes i seen those tutorials, but i been looking everywhere on how to add an online api instead of writing the values manually, i can add information manually but im missing where to put the online api instead – yandry santana Nov 04 '22 at 06:09
  • sorry wdym by online API – KcH Nov 04 '22 at 06:10
  • im building an MMORPG stats website, so this api gives information about the game. im on the point that i need to save that data to my mysql so i can put together more information about each player. if you want i can update the post with pictures and information so you see what im talking about – yandry santana Nov 04 '22 at 06:13
  • also `i can add information manually` ... do you mean in the MySQL application or via code ? if via code, then what issue are you facing updating the data from API ? – KcH Nov 04 '22 at 06:16
  • i created a backend code that connects to the database and a frontend code on the website that lets me write position, name, alliance, points and insert it into mysql. the issue im facing is inserting the data information directly from the api to the mysql not manually – yandry santana Nov 04 '22 at 06:19
  • so you are able to insert the data that is static but not from the frontend via API ? – KcH Nov 04 '22 at 06:22
  • exactly!, the mongoose code that i show here lets me do that for mongoose, but i don't know how to do that for mysql, i was hoping someone here knows and can give me a hand – yandry santana Nov 04 '22 at 06:23
  • don't mind me asking these many Q's as I don't have idea about node .... can you show how the db connection is ? and the way it is in w3schools set up won't that work ? – KcH Nov 04 '22 at 06:36
  • 1
    i dont mind the questions dont worry, thanks for asking them, yes i will update the code right now – yandry santana Nov 04 '22 at 06:42
  • if you check : app.post('/create', (req, res) => {.... that is the code that lets me insert data to mysql, if you have discord i can send you pictures and stuff of how it works better than here – yandry santana Nov 04 '22 at 06:54
  • https://stackoverflow.com/questions/74313299/insert-api-data-to-mysql-database – yandry santana Nov 04 '22 at 07:05
  • check my new post for more information – yandry santana Nov 04 '22 at 07:05
  • sure .... would be great adding `db` connection as well ... – KcH Nov 04 '22 at 07:06

0 Answers0