You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Express JS获取API的Items数组?解决undefined问题

问题解决:正确获取MongoDB文档中的items数组

核心错误分析

  1. Schema定义格式错误:你在schema.js中创建Schema时错误地用数组包裹对象(new Schema([{...}])),Mongoose的Schema构造函数仅接收单个对象参数,这种写法会导致数据映射完全失效。
  2. 缺失关键字段定义:你的MongoDB文档包含顶层的author、categories、items字段,但当前Schema未声明这些字段,Mongoose默认仅返回Schema中明确定义的字段,因此查询结果中不会出现items属性。

修正步骤

1. 修复schema.js的结构定义

调整为正确的Schema格式,添加顶层字段并定义items数组的嵌套结构:

const { Schema, default: mongoose } = require('mongoose');

// 定义items数组内单个元素的Schema
const BookItemSchema = new Schema({
  title: String,
  author: [String],
  publisher: String,
  publishedDate: String,
  description: String,
  pageCount: Number,
  printType: String,
  categories: [String],
  language: String,
  price: Number
});

// 定义顶层文档的Schema
const bookSchema = new Schema({
  author: [String],
  categories: [String],
  kind: String,
  items: [BookItemSchema] // 声明items为BookItemSchema类型的数组
});

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

2. 修正routes.js的查询逻辑

添加错误处理,确保正确提取items数组:

const express = require('express');
const router = express.Router(); // 使用Router实例而非重新创建app
const BookModel = require('./schema');

router.get('/books', async (req, resp) => {
  try {
    // 若仅需单个文档,用findOne()比find()更高效
    const bookDoc = await BookModel.findOne({});
    if (!bookDoc) {
      return resp.status(404).json({ message: '未找到相关书籍文档' });
    }
    const targetItems = bookDoc.items;
    console.log(targetItems);
    // 将结果返回给前端
    resp.json(targetItems);
  } catch (err) {
    console.error('查询错误:', err);
    resp.status(500).json({ message: '服务器内部错误' });
  }
});

module.exports = router;

3. 完善server.js的连接处理

为MongoDB连接添加错误捕获,避免静默失败:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const router = require('./routes');

// 添加MongoDB连接的状态反馈
mongoose.connect('mongodb://localhost:27017/book')
  .then(() => console.log('已连接MongoDB'))
  .catch(err => console.error('MongoDB连接失败:', err));

app.use(express.static('static'));
app.use(router);

app.listen(5000, () => {
  console.log("Server is running at http://127.0.0.1:5000");
});

验证结果

重启服务器后,发送GET请求到/books,控制台将正确输出items数组内容,前端也会收到该数组数据。

内容的提问来源于stack exchange,提问作者Sandy_Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 05:24:17