Laravel对接MongoDB注册后用户数据不显示问题排查
Laravel MongoDB注册后用户数据未写入问题排查
问题背景
原基于SQL实现的用户注册功能切换为MongoDB对接后,完成注册操作却发现MongoDB集合中未生成对应用户数据,怀疑是否因会话创建问题导致,请求排查代码错误。
待排查代码
<?php namespace App\Http\Controllers\Backend\V2\Member\Register; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Mongodb\User; use Validator; use App\Exceptions\ApplicationError; use Log; class Store extends Controller { public function __invoke(Request $request) { try { $data = $request->all(); $formValidation = Validator::make($data, [ 'name' => 'required|min:1|max:20', 'surname' => 'required|min:1|max:20', 'email' => 'required|email', 'phone' => 'required|min:1|max:20', 'password' => 'required|min:1|max:16|confirmed', ]); if ($formValidation->fails()) { $errorMessage = is_array($formValidation->errors()->getMessages()) ? current(data_get($formValidation->errors()->getMessages(), '*.0')) : $formValidation->errors()->first(); return response()->json(["status" => "error", "message" => __('lang-account.'.$errorMessage)], 200); } unset($data["password_confirmation"]); $existingUser = User::where('email', $data['email'])->first(); if ($existingUser) { throw new ApplicationError(__('lang-account.app.avaliable_email')); } // 哈希密码 $data['password'] = bcrypt($data['password']); User::create($data); $request->session()->regenerate(); return response()->json(['status' => 'success']); } catch (ApplicationError $e) { $errors = $e->getMessageArr(); return response()->json(['status' => 'error', 'message' => collect($errors)->first()], 200); } catch(Exception $e) { Log::error(__CLASS__." ".$e->getMessage()." ".$e->getFile()." ".$e->getLine()); $errors[] = __('lang-account.app.unkown_error').' '.__('lang-account.app.unkown_error'); return response()->json(['status' => 'error', 'message' => $errors]); } } }
核心错误排查点
1. MongoDB模型配置错误
这是最可能的原因:
- 继承类错误:
App\Models\Mongodb\User模型需继承Jenssegers\Mongodb\Eloquent\Model,而非Laravel默认的Illuminate\Database\Eloquent\Model,否则无法正确操作MongoDB - 集合名未指定:需在模型中通过
protected $collection = 'users';明确指定MongoDB集合名称,若未指定,Laravel会自动将模型名复数化,若集合名不一致会导致写入无数据 - 批量赋值权限缺失:
User::create($data)依赖模型的批量赋值配置,需在模型中定义protected $fillable = ['name', 'surname', 'email', 'phone', 'password'];(包含所有要写入的字段),或者设置protected $guarded = [];允许所有字段批量赋值,否则数据会被过滤无法写入
2. 全局Exception捕获失败
代码中catch(Exception $e)未引入全局Exception命名空间,会导致无法捕获非ApplicationError的异常(比如MongoDB连接异常、批量赋值异常等)。这些异常会直接抛出但不会被当前catch块捕获,导致接口返回成功但实际写入失败。
修复方案:
- 在文件顶部添加
use Exception; - 或者将
catch(Exception $e)改为catch(\Exception $e)(使用全局命名空间)
3. 会话操作与数据写入无关
$request->session()->regenerate();是会话重生成操作,仅用于防止会话固定攻击,和MongoDB写入用户数据没有直接关联,不是导致数据未写入的原因,无需在此处排查会话问题
4. 日志排查补充建议
在User::create($data)前后添加日志,确认代码执行流程:
Log::info('准备写入用户数据', $data); $user = User::create($data); Log::info('用户数据写入完成', ['user_id' => $user?->_id]);
通过日志可以明确是写入前的逻辑分支问题,还是写入过程中出现了未被捕获的异常
内容的提问来源于stack exchange,提问作者user21471995
相关产品推荐
相关产品推荐

