MongoDB中.save()函数无法正常工作问题求助
MongoDB
.save() 无法工作的问题排查与修复 问题根源梳理
从你的代码中可以定位到几个直接导致保存失败的问题,同时还有一些需要优化的细节:
Mongoose连接选项拼写错误
index.js中连接配置的userNewUrlParser是拼写错误,正确参数名应为useNewUrlParser,错误的参数会导致连接配置失效,可能数据库并未真正建立连接。Schema验证属性拼写错误
User.js中字段的require: true需改为required: true,这是Mongoose字段必填验证的正确属性名,拼写错误会导致验证逻辑异常。未输出具体错误信息
auth.js中.save()的回调仅返回通用错误,无法看到具体失败原因,不利于排查问题。路由方法选择不当 + 密码未加密
注册操作使用GET方法不符合REST规范,且直接明文存储密码存在安全风险,应该改用POST并通过bcrypt加密密码。
修正后的代码示例
1. index.js(修复数据库连接)
const express = require("express"); const app = express(); const dotenv = require("dotenv"); const helmet = require("helmet"); const morgan = require("morgan"); const mongoose = require("mongoose"); // 中间件 app.use(express.json()); app.use(helmet()); app.use(morgan("common")); // 路由引入 const authUser = require("./routes/auth"); // 加载环境变量 dotenv.config(); // 修复Mongoose连接配置 mongoose.connect(process.env.MONGO_PATH, { useNewUrlParser: true, useUnifiedTopology: true }, (err) => { if (err) { console.error("MongoDB连接失败:", err); return; } console.log("Connected to MongoDb"); }) app.use("/api/auth", authUser); app.listen(9000, () => { console.log("Server is Running..."); })
2. User.js(修复Schema验证)
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type: String, required: true, // 修正拼写 unique: true, // 建议添加唯一约束,避免重复用户名 }, password: { type: String, required: true, // 修正拼写 } }); const User = mongoose.model("User", UserSchema); module.exports = User;
3. auth.js(修复保存逻辑 + 安全优化)
const router = require("express").Router(); const User = require("../models/User"); const bcrypt = require("bcrypt"); // 改用POST路由处理注册 router.post("/register", async (req, res) => { try { // 先检查用户名是否已存在 const existingUser = await User.findOne({ username: req.body.username }); if (existingUser) { return res.status(400).json({ msg: "用户名已存在" }); } // 加密密码 const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(req.body.password, salt); const newUser = new User({ username: req.body.username, // 从请求体动态获取参数 password: hashedPassword }); const savedUser = await newUser.save(); res.status(200).json({ msg: "数据保存成功", user: { id: savedUser._id, username: savedUser.username } }); } catch (err) { console.error("保存用户错误详情:", err); // 控制台输出具体错误 res.status(500).json({ msg: "内部错误", errorDetail: err.message }); } }) module.exports = router;
测试方式
使用POST请求访问 localhost:9000/api/auth/register,请求体以JSON格式传递参数:
{ "username": "herovinay", "password": "herovinay" }
内容的提问来源于stack exchange,提问作者Vinay chandola
相关产品推荐
相关产品推荐

