Home > Net >  Fetch API Data In Node JS and Save In MongoDB Database
Fetch API Data In Node JS and Save In MongoDB Database

Time:10-18

I'm new to mongooseDB and i'm trying to insert data from this API to the database, it creates the Collection but not the documents, any idea what could i be doing wrong?

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

mongoose.connect("mongodb://localhost/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 getPlayers() {
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
    const response = await getPlayers.json();
    for (let i = 0; i < response.lenght; i  ) {

        const post = new Post({
            position: response[i]['position'],
            id: response[i]['id'],
            score: response[i]['score'],

        });
        post.save()

    }
}
getPlayers();```

CodePudding user response:

MongoDB provides Api to insert many documents at the same time, example below.

// check if your mongoDb is connected
mongoose.connect(URI).then(err => {
  if(err) console.error({err});
  else console.info("Database Connected");
});


async function getPlayers() {
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
   try{
    const response = await getPlayers.json();

    // And then check if you are getting players
    console.log({response});

    const posts = response.map((player) => ({
            position: player['position'],
            id: player['id'],
            score: player['score'],

        }))
   // it's not required to await it, just to be sure it did insert
  await Post.insertMany(posts);
  }catch(error){
    console.log({error})
   }

}

CodePudding user response:

This line:

for (let i = 0; i < response.lenght; i ) {

response.length

now your array is empty so the save never happens

EDIT

Are you sure about the imports? Following code works:

//const fetch = require('fetch'); 
const mongoose = require('mongoose');


mongoose.connect("mongodb://localhost/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 getPlayers() {
    /*
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
    const response = await getPlayers.json();
    for (let i = 0; i < response.lenght; i  ) {
*/
        const post = new Post({
            position: '12',
            id: '15',
            score: '300',

        });
        post.save()

    } //} getPlayers();

enter image description here

CodePudding user response:

By default mongodb runs on localhost: 27017

Check your mongodb connection url

mongoose.connect('mongodb://localhost:27017/highscore')
  • Related