【问题标题】:UnhandledPromiseRejectionWarning: ReferenceError: book is not definedUnhandledPromiseRejectionWarning: ReferenceError: book is not defined
【发布时间】:2025-12-23 15:20:11
【问题描述】:

我遇到了一个问题,当我点击我的路线 addBook 时出现错误,例如 book is not defined 不知道我在哪里,请尝试修复我的代码。如果您对我的代码有任何疑问,请告诉我。

route.js

这是我编写所有逻辑的 route.js 文件

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;

产品.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);

目录.js

这是分类模型。

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);

【问题讨论】:

  • 您能否分享整个错误,而不仅仅是 error.message 以及您发送的请求的正文?

标签: node.js mongodb express mongoose


【解决方案1】:
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);
});

嘿兄弟! 你写了一个很好的代码,但是你在 catch 块之后犯了一个小错误,你正在记录 book 这是在 try 块中定义的,并且 book 变量不能在该框之外访问,因为它的局部变量只能是在 try 块中使用 如果您想在try{} catch(){} 块之外使用该变量,则使用var 定义它

只需检查以下链接 geeksforgeeks.org/global-and-local-variables-in-javascript

黑客愉快:)

【讨论】:

    最近更新 更多