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

本地运行Mongoose连接报uri未定义错误,FreeCodeCamp挑战无法完成求助

Hey there! Let's break down why you're hitting that uri undefined error locally (even though things work on Heroku) and get your setup fixed so you can nail those FreeCodeCamp challenges.

First, the root cause of the connection error

Your Heroku app works because you've set the MONGO_URI as an environment variable directly in Heroku's settings. But locally, process.env.MONGO_URI is coming up undefined for a simple reason: dotenv is looking for a file named .env, but you have sample.env.

Step-by-step fixes

Let's walk through each fix to get your local connection working:

  1. Rename your environment file
    Rename sample.env to .env in your project root (same directory as myApp.js and package.json). Dotenv automatically loads variables from a file named .env by default, so this will make your MONGO_URI accessible to process.env.

  2. Clean up the .env file format
    Remove the quotes around your MONGO_URI value. The correct format for .env variables doesn't require quotes, and leaving them in can sometimes cause unexpected issues (like extra characters in your URI). Your .env should look like this:

    MONGO_URI=mongodb+srv://password2:rhyme@cluster0.77bp9.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
    
  3. Verify dotenv is installed and loaded correctly
    Make sure you've installed dotenv locally by running:

    npm install dotenv
    

    Your current code has require("dotenv").config(); at the top, which is the right order (load env vars before connecting to MongoDB), so that part is good.

  4. Add connection logging to debug
    To confirm your connection works, update your mongoose connect code to include success/error logs. This will let you see immediately if the connection is working:

    require("dotenv").config();
    const mongoose = require("mongoose");
    
    mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => console.log("✅ MongoDB connected successfully!"))
    .catch(err => console.error("❌ MongoDB connection failed:", err));
    

Why your model challenge isn't working

Once you fix the connection error, your model challenge should start working. The model code you wrote is correct (as you confirmed), but Mongoose can't create or use models if it's not connected to the database first. The connection failure was blocking all subsequent Mongoose operations.

Give these steps a try, and your local setup should match Heroku's behavior, letting you complete those challenges smoothly!

内容的提问来源于stack exchange,提问作者Hunter Scott Lacefield

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:52:29