![](/img/trans.png)
[英]The `uri` parameter to `openUri()` must be a string, got "undefined"
[英]Error : The `uri` parameter to `openUri()` must be a string, got “undefined”
我制作了一个播种器文件以在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.
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.
学生文件包含学生数据,学生文件是 model 文件,如果有人请帮助我...
播种机.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;
我认为这可能是问题所在:
这些函数被定义为async
,因此它们返回Promise ,但是您无需等待 Promise 被满足或拒绝就可以调用它们,特别是在connectDB()
的情况下。
尝试在connectDB()
调用之前添加await
语句,如下所示:
await connectDB();
//... the rest of the code
必须发生的是,在程序的主要部分运行并完成之后完成了对连接的调用,但是您需要在导入/销毁数据之前连接数据库,对吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.