Mongoose Schema未在MongoDB中创建带默认值的字段问题
问题:MongoDB + Mongoose 中默认值为null的字段未存入文档
我正在开发React Native应用的用户注册功能,技术栈为Express.js、MongoDB及Mongoose。已定义包含name、age、gender、city字段的User Schema,这些字段默认值均设为null,但注册新用户时,这些字段并未带着默认值出现在MongoDB文档中。
Schema定义(user.js)
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String, default: null }, age: { type: Number, default: null }, gender: { type: String, default: null }, city: { type: String, default: null }, }); module.exports = mongoose.model('User', userSchema);
注册逻辑(server.js)
const newUser = new User({ email, password: hashedPassword, name: null, age: null, gender: null, city: null, }); const savedUser = await newUser.save(); console.log('Saved User:', savedUser);
实际现象
服务器控制台输出
Saved User: { email: 'Lkdlm@kcmld.com', password: '$2a$10$knk8jOidiFwnSSFm8QhQj.ndDefZ2oCiV81an6twgjMa2edhanwj.', _id: new ObjectId("64d7ada414deacac8e92c7be"), __v: 0 }
MongoDB Shell中的文档
{ "_id" : ObjectId("64d7ada414deacac8e92c7be"), "email" : "Lkdlm@kcmld.com", "password" : "$2a$10$knk8jOidiFwnSSFm8QhQj.ndDefZ2oCiV81an6twgjMa2edhanwj.", "__v" : 0 }
预期与实际差异
- 预期:新注册用户的MongoDB文档包含
name、age、gender、city字段,且值为null - 实际:这些字段直接缺失,未被存入文档
已做排查
- 反复验证了User Schema和注册逻辑的代码定义
- 重启服务器并重新创建数据库
- 尝试通过MongoDB Compass手动添加带默认值的用户
解决方案
问题出在Mongoose的默认行为上:Mongoose默认开启minimize: true,会自动移除文档中值为null、undefined的字段。要保留这些字段,只需在创建Schema时关闭该选项:
修改后的user.js:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String, default: null }, age: { type: Number, default: null }, gender: { type: String, default: null }, city: { type: String, default: null }, }, { minimize: false }); // 添加该配置,关闭空值字段自动移除 module.exports = mongoose.model('User', userSchema);
修改后重新启动服务器,注册新用户时,name、age、gender、city字段就会带着null值存入MongoDB文档中。
内容的提问来源于stack exchange,提问作者htcdang
相关产品推荐
相关产品推荐

