【发布时间】:2022-08-14 00:06:00
【问题描述】:
我在 config.js 中编写以下代码以连接到 mongodb
const mongoose=require(\'mongoose\');
const PORT=3000;
const connectionString=`mongodb://localhost:3000:sale`;
mongoose.connect(connectionString,(err)=>{
(err)? console.log(\'Fail to connect to mongodb\'):console.log(\'Connect success.\');
});
module.exports=mongoose;
并在 model.js 中创建模型:
const { default: mongoose } = require(\"mongoose\");
const { stringify } = require(\"nodemon/lib/utils\");
const _product=mongoose.Schema({
id:{
type:Number,
require:true
},
name:{
type:String,
require:true
},
description:{
type:String,
require:false
}
});
module.exports=mongoose.model(\'product\',_product);
并在 app.js 中编写以下代码:
const express = require(\"express\");
const app=express();
// require(\'dotenv\').config();
require(\'./Database/config.js\');
const product=require(\'./model/model.js\');
const PORT=3000;
app.listen(PORT,\'Run on port \'+ PORT);
app.post(\'/insert\',async(req,res)=>{
const newProduct=new product({
name:\'GLX SHAHIN 3\',
id:1,
description:\'Newest iranian phone\'
});
try{
await newProduct.save();
res.send(`Inserted : ${newProduct}`);
}
catch(err){
res.send(err);
}
});
当我运行 npx nodemon app.js 或 node app.js 有时会出现 ENOTEFOUND 错误 EACCES 错误:
Fail to connect to mongodb
node:events:498
throw er; // Unhandled \'error\' event
^
Error: getaddrinfo ENOTFOUND Run on port 3000
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
Emitted \'error\' event on Server instance at:
at GetAddrInfoReqWrap.doListen [as callback] (node:net:1513:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:17) {
errno: -3008,
code: \'ENOTFOUND\',
syscall: \'getaddrinfo\',
hostname: \'Run on port 3000\'
请注意,我在每个端口上都收到这些错误,而不仅仅是在特定端口上。
-
您的 Nodejs 似乎运行良好,但无法连接到您的 Mongo 服务器。您的 mongo 是否在运行,如果是,在哪个端口下运行?
-
getaddrinfo ENOTFOUND表示无法将主机名转换为 IP 地址。这是意料之中的,因为您出于某种原因将Run on port 3000作为主机名,当然这不是主机名。您对app.listen的使用可能是错误的,请查看API 文档。 -
@Freeman_Lambda mongodb 不在每个端口上连接
标签: node.js error-handling dns port permission-denied