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

NextJS项目中从MongoDB获取带数据类型的查询结果方案问询

解决方案

步骤1:导入MongoDB类型并编写类型检测函数

首先导入MongoDB的ObjectId以识别特殊类型,再写一个函数判断字段的真实类型:

import clientPromise from "../../../lib/mongo/mongo";
import { ObjectId } from 'mongodb';

// 检测字段的真实MongoDB类型
function getFieldType(value) {
  if (value instanceof ObjectId) {
    return 'ObjectId';
  } else if (value instanceof Date) {
    return 'Date';
  } else if (Array.isArray(value)) {
    return 'Array';
  } else {
    return typeof value;
  }
}

步骤2:转换数据结构

编写转换函数,把MongoDB返回的文档转换成带类型信息的目标结构:

// 将文档转换为带类型的字段数组
function transformDocuments(documents) {
  return documents.flatMap(doc => {
    return Object.entries(doc).map(([key, value]) => {
      // ObjectId转为字符串方便前端处理
      const fieldValue = value instanceof ObjectId ? value.toString() : value;
      return {
        [key]: fieldValue,
        type: getFieldType(value)
      };
    });
  });
}

步骤3:修改API路由代码

更新API处理逻辑,移除不必要的连接/关闭操作(clientPromise已维护连接池),并应用数据转换:

export default async function handler(req, res) {
  const client = await clientPromise;
  try {
    const allData = await client
      .db()
      .collection(req.query.collection[0])
      .find({})
      .toArray();

    const transformedData = transformDocuments(allData);
    return res.status(200).json(transformedData);
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
}

说明

  • ObjectId识别:通过instanceof ObjectId判断,避免typeof返回object的模糊结果
  • 类型覆盖:包含Date、Array及所有基础数据类型
  • 连接优化:去掉client.connect()和client.close(),防止连接池被意外关闭导致后续请求失败

示例返回结果

[
  { "_id": "323030049934bwd", "type": "ObjectId" },
  { "name": "David", "type": "string" },
  { "active": false, "type": "boolean" },
  { "createTime": "2024-05-20T12:00:00.000Z", "type": "Date" }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:13:40