Nodejs - Problem sending a POST with object array

Asked

Viewed 703 times

3

I’m using Nodejs + Mongodb, and I’m trying to send an array of Book, via method POST, but somehow it’s giving problem, because when using Postman and clicking Send, it just returns me:

{
    "_id": "5c48cf81a90935079bb12035",
    "createdAt": "2019-01-23T20:33:05.595Z",
    "updatedAt": "2019-01-23T20:33:05.595Z",
    "__v": 0
}

The JSON I’m trying to send by Postman follows this template:

[
    {
        "title": "A menina que roubava livros",
        "description": "Uma garota que adorava ir pra biblioteca roubar livro",
        "url": "http://www.amenina.com.br",
        "date": "2018-02-01",
        "owner": "Paulo Coelho"
    }, 
    {
        "title": "A menina que roubava livros 2",
        "description": "Uma garota que adorava ir pra biblioteca roubar livro",
        "url": "http://www.amenina.com.br",
        "date": "2018-02-01",
        "owner": "Paulo Coelho"
    }
]

In short: I need to send a Schema (which will be just below here) via POST using Nodejs, but when I try, it returns the JSON above

Follows the related codes:

SCHEMA

[
    {
        title: String,
        description: String,
        url: String,
        data: String,
        owner: [String]
    }   
]

MODEL

const mongoose = require('mongoose')
const BookSchema = mongoose.Schema([
    {
        title: String,
        description: String,
        url: String,
        date: String,
        owner: String
    }], 
{
    timestamps: true
})
module.exports = mongoose.model('Book', BookSchema)

ROUTER

module.exports = (app) => {
    const books = require('../controllers/book.controller.js')
    app.post('/books', books.create)
    app.get('/books', books.findAll)
}

CONTROLLER

const Book = require('../models/book.model.js')
exports.create = (req, res) => {
    const book = new Book(
        {
            title: req.body.title || '',
            description: req.body.description || '',
            url: req.body.url || '',
            date: req.body.date,
            owner: req.body.owner
        }
    ) 

    book.save()
    .then(data => {
        res.send(data)
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Erro em comunicação com o servidor. Tente mais tarde"
        })
    })
}

console.log(req.body) before the method book save.() returns the completed data to me:

[ { title: 'A menina que roubava livros',
    description: 'Uma garota que adorava ir pra biblioteca roubar livro',
    url: 'http://www.amenina.com.br',
    date: '2018-02-01',
    owner: 'Paulo Coelho' },
  { title: 'A menina que roubava livros 2',
    description: 'Uma garota que adorava ir pra biblioteca roubar livro',
    url: 'http://www.amenina.com.br',
    date: '2018-02-01',
    owner: 'Paulo Coelho' } ]
  • Your question is a little vague. Could explain a little better the problem and what you want to do?

  • What problem? Showing error in console?

  • I got the description, tell me if it’s more readable, anything, I try to explain otherwise

  • It shows no error in the console, but does not send the data array correctly

  • Make a console.log(req.body) before saving the book and ask the question

  • It shows the completed data @Guilhermecostamilam

  • That’s what I thought, it receives an array but tries to save as if it were an object, what happens is that the result when creating a Book it returns an object undefined

  • Thank you guys, thank you all here, I got with the solution below!

Show 3 more comments

1 answer

1


you are sending an array, but you are saving it as if it were a single object. recommend that you send an Array in this form

{
books:[
    {
        "title": "A menina que roubava livros",
        "description": "Uma garota que adorava ir pra biblioteca roubar livro",
        "url": "http://www.amenina.com.br",
        "date": "2018-02-01",
        "owner": "Paulo Coelho"
    }, 
    {
        "title": "A menina que roubava livros 2",
        "description": "Uma garota que adorava ir pra biblioteca roubar livro",
        "url": "http://www.amenina.com.br",
        "date": "2018-02-01",
        "owner": "Paulo Coelho"
    }
]
}

so you can access JSON from the req.body.books; example:

    const books = req.body.books;

    for (let i = 0; i < books.books.length; i++) {
        const item = books[i];

        const book = new Book(
        {
            title: item.title || '',
            description: item.description || '',
            url: item.url || '',
            date: item.date,
            owner: item.owner
        }) 

        book.save()

    }
  • 1

    You can simplify the loop and use the syntax for (const item of books) ...

  • 1

    In this case it would also be interesting to use the Promise.all to make a better handling of mistakes.

  • 1

    It worked! Thank you very much man, and thank you all here too!

Browser other questions tagged

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