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

NodeJS连接MongoDB Atlas遇ReferenceError: string未定义问题求助

Fixes for Your Node.js + MongoDB Atlas Setup

1. Resolve the ReferenceError in userModel.js

The error occurs because Mongoose schema types require capitalized constructor names (e.g., String, not lowercase string). Here's the corrected file:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    email: {
        type: String, // Corrected from string to String
        required: true
    },
    password: {
        type: String, // Corrected from string to String
        required: true
    },
    confirmpassword: {
        type: String, // Corrected from string to String
        required: true
    }
}, { timestamps: true })

const User = mongoose.model('User', userSchema);
module.exports = User;

Note: Your signup form doesn’t include a confirmpassword field—either add it to the form or remove this field from the schema to avoid validation failures.

2. Correct Form Action in signup.ejs

The form’s action attribute points to the wrong path. Since your server maps /signup to signupRoutes.js, update the action to /signup:

<form action="/signup" method="post">
     <label for="email">Email:</label>
     <input type="email" id="email" name="email" required><br><br>
     <label for="password">Password:</label>
     <input type="password" id="password" name="password" required><br><br>
     <!-- Uncomment below if you keep confirmpassword in the schema -->
     <!-- <label for="confirmpassword">Confirm Password:</label>
     <input type="password" id="confirmpassword" name="confirmpassword" required><br><br> -->
     <input type="submit" value="Submit">
</form>

Also updated password input type to password for security and added required attributes for basic client-side validation.

3. Fix Route Logic in signupRoutes.js

  • Use router.post instead of app.post (you’re working with a router instance, not the main app)
  • Add async/await handling for user.save() to avoid unhandled promise rejections
  • Align the route path with how the router is mounted (use / instead of /signup)

Corrected file:

const express = require('express');
const router = express.Router();

const User = require('../models/userModel');

router.get('/', (req, res) => {
    res.render('./signup');
    // Remove res.end()—res.render already sends the response
});

router.post('/', async (req, res) => {
    try {
        const user = new User({
            email: req.body.email,
            password: req.body.password,
            confirmpassword: req.body.confirmpassword // Include this if you added the field to the form
        }); 
        await user.save();
        res.redirect('/index'); // Redirect to your homepage route
    } catch (err) {
        console.error(err);
        res.status(400).send('Failed to create user');
    }
});

module.exports = router;

4. Add Body Parsing Middleware in server.js

Without this middleware, req.body will be undefined when handling POST requests. Add this line before your route declarations:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const ejs = require('ejs');

const homepageRoutes = require('./routes/homepageRoutes');
const signupRoutes = require('./routes/signupRoutes');
const loginRoutes = require('./routes/loginRoutes');

const dotenv = require('dotenv');
dotenv.config();
const dbusername= process.env.DB_USERNAME;
const dbpassword= process.env.DB_PASSWORD;
const dbURI = `mongodb+srv://${dbusername}:${dbpassword}@testingcluster.ix9mpsg.mongodb.net/?retryWrites=true&w=majority`; // Added const to avoid global scope leak

mongoose.connect(dbURI).then((result) => app.listen(4000)).catch((err) => console.log(err));

app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(express.urlencoded({ extended: true })); // Add this line to parse form data

app.use("/index", homepageRoutes);
app.use("/signup", signupRoutes);
app.use("/login", loginRoutes);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:01:11