我正在使用 next js 13.4.19。我制作了一个 GET api 并尝试访问 mongodb 数据库中可用的数据。但是当我尝试映射数据时它显示错误 错误:data?.map 不是函数。 这是我的产品架构
import mongoose from "mongoose";
const productSchema = new mongoose.Schema({
name: String,
price: Number,
category: String,
});
export const Product =
mongoose.models.products || mongoose.model("products", productSchema);
这是我的 GET API
import { dbStr } from "@/database/connection";
import { Product } from "@/model/product/product";
import mongoose from "mongoose";
import { NextResponse } from "next/server";
export async function GET() {
let data = [];
try {
await mongoose.connect(dbStr);
data = await Product.find();
} catch (error) {
console.log(error);
}
return NextResponse.json({ data }, { success: true });
}
我已经测试了 API 工作正常并显示数据如下
{
"data": [
{
"_id": "64fd823b07208cd28468b70e",
"name": "samsung",
"price": 1200,
"category": "mobile",
"__v": 0
},
{
"_id": "64fe1aa2e801f1d8af66b362",
"name": "abc",
"price": 2,
"category": "abc",
"__v": 0
},
{
"_id": "64fe1ae7e801f1d8af66b366",
"name": "shehz",
"price": 200,
"category": "gg",
"__v": 0
},
]
}
但是当我尝试从上面给定的 api 获取数据时,我遇到了错误
import React from "react";
async function getData() {
const res = await fetch("http://localhost:3000/api/products");
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error("Failed to fetch data");
}
return res.json();
}
const GetProducts = async () => {
const data = await getData();
return (
<div>
<h1>Get All Products Data</h1>
<table>
<thead>
<tr>
<td>name</td>
<td>price</td>
<td>category</td>
</tr>
</thead>
<tbody>
{data?.map((item) => {
return (
<tr key={item._id}>
<td>{item.name}</td>
<td>{item.price}</td>
<td>{item.category}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default GetProducts;
在服务器端我面临这个问题
error TypeError: data?.map is not a function
at GetProducts (./src/component/GetProducts.js:69:41)
26 | </thead>
27 | <tbody>
> 28 | {data?.map((item) => {
| ^
29 | return (
30 | <tr key={item._id}>
31 | <td>{item.name}</td>
你能试试这个吗? data 内部有一个关键数据,您需要访问该数据才能对其进行映射。
const {data} = await getData();