Home > Mobile >  UnhandledPromiseRejectionWarning: ReferenceError: book is not defined
UnhandledPromiseRejectionWarning: ReferenceError: book is not defined

Time:01-29

I stuck with a problem, when I hit my route addBook then getting an error like book is not defined don't know where I am please try to fix my code. if you have any query on my code please let me know.

Error page

route.js

This is the route.js file where I wrote my all logics

const express = require("express");
const router = express.Router();
const Publisher = require('../model/Categary');
const Book = require('../model/Product');

// const {addCatogary} = require('../controllers/Product');
// router.get('/addcatogary',addCatogary);

router.post("/addPublisher", async (req, res) => {
  try {
    //validate req.body data before saving
    const publisher = new Publisher(req.body);
    await publisher.save();
    res.status(201).json({ success: true, data: publisher });
    console.log(publisher);
  } catch (err) {
    res.status(400).json({ success: false, message: err.message });
  }
  console.log(err);
  
});

router.post("/addBook", async (req, res) => {
  try {
    //validate data as required

    const book = new Book(req.body);
    // book.publisher = publisher._id; <=== Assign user id from signed in publisher to publisher key
    await book.save();

    const publisher = await Publisher.findById({ _id: book.publisher });
    publisher.publishedBooks.push(book);
    await publisher.save();

    //return new book object, after saving it to Publisher
    res.status(200).json({ success: true, data: book });
  } catch (err) {
    res.status(400).json({ success: false, message: err.message });
  }
  console.log(book);
});

router.get("/publishers", async (req, res) => {
  try {
    const data = await Publisher.find().populate({
      path: "booksPublished",
      select: "name publishYear author",
    });
    res.status(200).json({ success: true, data });
  } catch (err) {
    res.status(400).json({ success: false, message: err.message });
  }
  console.log(data)
});

module.exports = router;

Product.js

const mongoose= require('mongoose');
const {Schema} = require('mongoose');

const bookSchema = new Schema({
   name: String,
   publishYear: Number,
   author: String,
   publisher: {
      type: Schema.Types.ObjectId,
      ref: 'Publisher',
      required: true
   }
},
{timestamps: true});

module.exports = mongoose.model('Book', bookSchema);

Catogary.js

This is the Catogary model.

const mongoose = require('mongoose');
const {Schema} = require('mongoose');

const publisherSchema = new Schema({
   name: String,
   location: String
},
   {timestamps: true}
);

publisherSchema.virtual('booksPublished', {
   ref: 'Book', //The Model to use
   localField: '_id', //Find in Model, where localField 
   foreignField: 'publisher', // is equal to foreignField
});

// Set Object and Json property to true. Default is set to false
publisherSchema.set('toObject', { virtuals: true });
publisherSchema.set('toJSON', { virtuals: true });


module.exports = mongoose.model('Publisher', publisherSchema);

CodePudding user response:

The error that your try-catch block threw says "Book validation failed: publisher: Path 'publisher' is required." You're creating Book() with req.body, does it have the publisher in there? You've set publisher in bookSchema to be required, so it'll have to be there for it to validate properly.

CodePudding user response:

router.post("/addBook", async (req, res) => {
  try {
    //validate data as required

    const book = new Book(req.body);
    // book.publisher = publisher._id; <=== Assign user id from signed in publisher to publisher key
    await book.save();

    const publisher = await Publisher.findById({ _id: book.publisher });
    publisher.publishedBooks.push(book);
    await publisher.save();

    //return new book object, after saving it to Publisher
    res.status(200).json({ success: true, data: book });
  } catch (err) {
    res.status(400).json({ success: false, message: err.message });
  }
  console.log(book);
});

hey brother! you have written a nice code but you have made a small mistake after catch block you are logging book which is defined inside try block and that book variable can not be accessed outside of that box because its local variable and can be only used inside try block if you wanted to used that variable outside of try{} catch(){} block defined it with var

just check below link geeksforgeeks.org/global-and-local-variables-in-javascript

happy hacking :)

  •  Tags:  
  • Related