【问题标题】:Error : The `uri` parameter to `openUri()` must be a string, got "undefined"错误:`openUri()` 的 `uri` 参数必须是字符串,得到“未定义”
【发布时间】:2021-05-21 17:19:30
【问题描述】:

我制作了一个 seeder 文件以在 MongoDB 数据库中添加数据,但出现此错误, Error : The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. 学生文件包含学生数据,学生文件是模型文件, 如果有人请帮助我...

Seeder.js

const students = require("./data/students");
const Student = require("./models/Student");
const dotenv = require("dotenv");
const connectDB = require("./config/db");

dotenv.config("../.env");
connectDB();

const importData = async () =>{
    try{
        await Student.deleteMany();
        await Student.insertMany(students)
        console.log("data imported");
        process.exit();
    }catch(err){
        console.log("Error : "+err);
        process.exit(1);
    }
}

const destroyData = async () =>{
    try{
        await Student.deleteMany();
        console.log("data destroyed");
        process.exit();
    }catch(err){
        console.log("Error : "+err);
        process.exit(1);
    }
}

if(process.argv[2] === "-d"){
    destroyData();
}else{
    importData();
}

这是我的连接文件 db.js

const mongoose = require("mongoose");

const connectDB = async () =>{
    try{
        const conn = await mongoose.connect(process.env.ATLAS_URI,
            {
                useCreateIndex: true,
                useNewUrlParser: true,
                useUnifiedTopology: true
            })
            console.log(`mongoDB connected successfully`);
    }catch (err){
        console.log(`Error : ${err.message}`);
        process.exit(1);
    }
}

module.exports = connectDB;

【问题讨论】:

  • 确保mongoose.connect() 接收到正确的参数。 process.env.ATLAS_URI 定义了吗?
  • 是的,它正在接收正确的参数,process.env.ATLAS_URI 也已定义

标签: javascript node.js mongodb express mongoose


【解决方案1】:

我认为这可能是问题所在:

这些函数被定义为async,所以它们返回一个Promise,但是你在没有等待Promise被实现或拒绝的情况下调用它们,特别是在connectDB()的情况下。

尝试在connectDB() 调用之前添加await 语句,如下所示:

await connectDB();

//... the rest of the code

必须发生的是,在程序的主要部分运行并完成之后调用连接,但是您需要在导入/销毁数据之前连接数据库,对吧?

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 2021-05-22
    • 2021-03-24
    • 1970-01-01
    • 2021-06-17
    • 2019-10-05
    • 2023-02-11
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多