如何在Mongoose模型中将JSON响应字段first_name映射为firstName?
当然可行!Mongoose轻松实现字段名映射
完全可行!Mongoose刚好提供了灵活的配置来满足这种「代码里用驼峰、对外返回下划线」的需求,我给你两种常用的实现方式,你可以根据自己的场景选择:
方案一:字段别名(Alias)—— 最省心的方式
这种方式直接在Schema定义时给字段设置别名,让你在代码里用firstName操作模型,同时数据库存储和对外返回的JSON都会使用first_name。
代码示例
const mongoose = require('mongoose'); const { Schema } = mongoose; // 定义Schema时给字段绑定别名 const userSchema = new Schema({ firstName: { type: String, alias: 'first_name' // 核心配置:模型字段firstName对应数据库/JSON的first_name }, lastName: { type: String, alias: 'last_name' } }); const User = mongoose.model('User', userSchema);
使用场景
- 创建文档:两种字段名都能生效
// 用模型里的驼峰字段名 const user1 = new User({ firstName: 'John', lastName: 'Doe' }); // 或者用下划线别名 const user2 = new User({ first_name: 'Jane', last_name: 'Smith' }); await user1.save(); await user2.save();
- 查询文档:同样支持两种字段名查询
const john = await User.findOne({ firstName: 'John' }); const jane = await User.findOne({ first_name: 'Jane' });
- 返回JSON:自动输出下划线格式的字段
console.log(john.toJSON()); // 输出结果:{ _id: ObjectId("..."), first_name: 'John', last_name: 'Doe', __v: 0 }
方案二:JSON转换钩子(Transform)—— 自定义输出格式
如果你希望数据库里存储驼峰格式的firstName,只是在对外返回JSON时转成first_name,可以用Schema的toJSON配置里的transform函数来做字段重命名。
代码示例
const userSchema = new Schema({ firstName: String, lastName: String }, { // 配置JSON转换规则 toJSON: { transform: function(doc, ret) { // 把驼峰字段转成下划线 ret.first_name = ret.firstName; ret.last_name = ret.lastName; // 删除原来的驼峰字段 delete ret.firstName; delete ret.lastName; // 可选:删掉不需要返回的字段(比如__v) delete ret.__v; } } }); const User = mongoose.model('User', userSchema);
使用效果
const user = new User({ firstName: 'John', lastName: 'Doe' }); await user.save(); // 数据库里存储的是firstName和lastName console.log(user.toJSON()); // 输出结果:{ _id: ObjectId("..."), first_name: 'John', last_name: 'Doe' }
总结
- 如果希望数据库和JSON响应统一用下划线格式,代码里用驼峰,选方案一;
- 如果数据库存驼峰,仅对外返回时转下划线,选方案二。
内容的提问来源于stack exchange,提问作者Raj Chaudhary
相关产品推荐
相关产品推荐

