MERN Stack Tutorial - Book Store Project

When post request ran in Postman an instance is created in the DB, but no data filed values are sent

import express from "express";
import {PORT, mongoDBURL} from "./config.js";
import mongoose from "mongoose";
import {Book} from "./models/bookModel.js";

const app = express();

app.use(express.json());

// Create HTTP Route requests
app.get('/', (request, response)=>{
    console.log(request)
    return response.status(234).send("Welcome to MERN Stack Tutorial");
});

//--> Route to save a new book: this is an async process 
app.post("/books", async(request, response)=>{
    try{ //"try validating the input"
        if(
            !request.body.title ||
            !request.body.author ||
            !request.body.publishYear  
          ) {
            return response.status(400).send({
                message: "Send all required fields: title, author, publishYear",
            });
          }
          const newBook = {
            title: request.body.title,
            author: request.body.author,
            publishYear: request.body.publishYear
          };

          const book = await Book.create(newBook);
          console.log(book);
          return response.status(201).send(book);
    } catch(error){
        console.log(error.message);
        response.status(500).send({message: error.message});
    }
});

mongoose.connect(mongoDBURL)
    .then(() => {
        console.log("App connected to database");
        app.listen(PORT, ()=>{
            console.log(`App is listening to port: ${PORT}`);
        }); 
    })
    .catch((error)=>{
        console.log(error);
    });`Preformatted text`
  • what do you see in this console log

or perhaps you can also try looin onto their “save” method instead, this article here shows how The `create()` Function in Mongoose - Mastering JS

happy coding :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.