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

Next 13与Mongoose:如何自动将ObjectID转为字符串?

解决Next.js 13服务器组件中MongoDB ObjectId自动转字符串的问题

方法1:查询时配置lean的transform选项

直接在lean()中定义转换逻辑,自动将_id转为字符串,无需手动遍历:

const services = await Service.find().lean({
  transform: (doc) => {
    doc.id = doc._id.toString();
    delete doc._id;
    // 可选:移除不需要的__v字段
    delete doc.__v;
    return doc;
  }
});

该方法无需修改Schema,仅对当前查询生效,灵活度高。

方法2:给Schema配置全局转换规则

如果希望所有查询(包括lean())都自动处理_id,可以在Schema定义时添加toJSON和toObject选项:

const serviceSchema = new mongoose.Schema(
  {
    category: String,
    // 其他字段定义...
  },
  {
    toJSON: {
      transform(doc, ret) {
        ret.id = ret._id.toString();
        delete ret._id;
        delete ret.__v;
      }
    },
    toObject: {
      transform(doc, ret) {
        ret.id = ret._id.toString();
        delete ret._id;
        delete ret.__v;
      }
    }
  }
);

注意:Mongoose 6.0+版本中lean()可兼容该转换规则,低版本需搭配lean({ virtuals: true })生效。

方法3:使用Mongoose插件自动处理

借助mongoose-lean-id插件,全局或单Schema注册后,所有lean查询结果会自动生成字符串类型的id字段:

  1. 安装插件:npm install mongoose-lean-id
  2. 注册插件:
// 全局注册(所有Schema生效)
const mongoose = require('mongoose');
const leanId = require('mongoose-lean-id');
mongoose.plugin(leanId);

// 或单个Schema注册
serviceSchema.plugin(leanId);

执行Service.find().lean()后,结果会同时保留原_id和字符串类型的id字段,可按需删除_id。

方法4:JSON序列化 hack(不推荐)

若不想修改查询或Schema,可通过JSON序列化强制转换ObjectId为字符串:

const services = JSON.parse(JSON.stringify(await Service.find().lean()));

⚠️ 此方法会将Date、Decimal128等特殊类型转为字符串,可能导致类型丢失,仅适合字段类型简单的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:12:37