Error trying to post on Mongodb with Insomnia

Asked

Viewed 888 times

-2

Hello, I am trying to insert a data in the database (Mongodb)using the POST type, I am using Insomnia to perform the inserts tests but when I try I get a return of errors by the nodejs terminal, as shown below:

(Ode:13000) Unhandledpromiserejectionwarning: Typeerror: Cannot read Property 'split' of Undefined at parseStringAsArray (C: Users rodri Onedrive Documents Projects devMaps backend src utils parseStringAsArray.js:2:26) at store (C: Users rodri Onedrive Documents Projects devMaps backend src controllers Devcontroller.js:48:32) at process. _tickCallback (Internal/process/next_tick.js:68:7) (Node:13000) Unhandledpromiserejectionwarning: Unhandled Promise rejection. This error originated either by Throwing Inside of an async Function without a catch block, or by rejecting a Promise which was not handled with . catch(). (rejection id: 1) (Node:13000) [DEP0018] Deprecationwarning: Unhandled Promise rejections are deprecated. In the Future, Promise rejections that are not handled will terminate the Node.js process with a non-zero Exit code.

I noticed that the error occurs because it informs that the split is not set.

Follow the two programs below:

parseStringAsArray.js

module.exports = function parseStringAsArray(arrayAsString){
return arrayAsString.split(',').map(tech => tech.trim());

}

Devcontroller.js

const axios = require('axios');
const Dev = require("../models/Dev");
const parseStringAsArray = require('../utils/parseStringAsArray');

module.exports = {

    async index(request, response) {
        const devs = await Dev.find();
        return response.json(devs);

    },

    async store(request, response) {

        const { github_username, techs, latitude, longitude } = request.body;

        let dev = await Dev.findOne({ github_username });

        if(!dev) {

            const apiResponse = await axios.get(`https://api.github.com/users/${github_username}`);
    
            const { name = login, avatar_url, bio } = apiResponse.data;
    
            const techsArray = parseStringAsArray(techs);
            
            const location = {
                type: 'Point',
                coordinates: [longitude, latitude],
            };
    
            dev = await Dev.create({
                github_username,
                name,
                avatar_url,
                bio,
                techs: techsArray,
                location,
            });

        }
        
        return response.json(dev);
    }

};

And this is the JSON I’m trying to insert into Mongodb:

inserir a descrição da imagem aqui

Could someone please help me? I’ve been trying for more than 2 days to find a solution but I don’t know what else to do!

Thank you

1 answer

-1

From what I saw of your code, the error occurs before recording on Mongo, the reason for the error is that it did not load "techs" from the body of your Request post.

You can confirm this by displaying the request body content on the console

async store(request, response) {
    console.log(request.body);
    const { github_username, techs, latitude, longitude } = request.body;
    console.log(github_username);
    console.log(techs);
    console.log(latitude);
    console.log(longitude);
}

One way to avoid the problem would be to check whether "techs" was received before performing the "parseStringAsArray" function"

const techsArray = []
if (techs){
    techsArray = parseStringAsArray(techs);
}

It may be that the problem is in your src/index.js file, make sure you have enabled middleware to receive data via JSON before calling the routes.

app.use(express.json());

Contents of the index file:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const http = require('http');

const routes = require('./routes');
const { setupWebsocket } = require('./websocket')

const app = express();
const server = http.Server(app);

setupWebsocket(server);

mongoose.connect('mongodb+srv://omnistack:[email protected]/week10?retryWrites=true&w=majority', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.use(cors());
app.use(express.json());
app.use(routes);

server.listen(3333);
  • Bins, Graduate for help and I will validate all the tips that Oce passed me and return to give feedback.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.