【问题标题】:Mongodb connected on nodejs and localhost keeps on reloading在nodejs和localhost上连接的Mongodb不断重新加载
【发布时间】:2022-01-21 01:59:05
【问题描述】:

我正在尝试使用 nodejs express 脚本连接到我的后端 mongodb 5.0.5。 使用 nodemon 运行 app.js 时,它显示您的 mongodb 已连接,但在 localhost 上它会继续重新加载,而不会出现任何错误堆栈跟踪。

我在模型中使用猫鼬模型,就像在 nodejs 中的 MVC 中一样。不知道为什么它没有在 localhost 上运行,当我上次使用这些文件时它工作正常。

这是我的文件:

app.js

// imports
  const express = require('express')
 const bodyParser = require('body-parser')
 const cors = require('cors')
 const { append } = require('express/lib/response')
  const zomatoRoutes = require('./Routes/zomato')
  const mongoose = require('mongoose')

     // create express server

     var app = express()

     //listen to a port

     app.listen(7878, () => {
       console.log('app running on port 7878');
   })

     app.use(bodyParser.json())

    //connect mongodb   
    mongoose.connect('mongodb://localhost/zomato', () => {
  console.log("MongoDB Connected");},
   e => console.log(e)
   ) 

   // Middleware routes
   app.use('/zomato', zomatoRoutes)

   app.use(cors())

模型>locations.js

const mongoose = require('mongoose')

const locationSchema = new mongoose.Schema({

name: {
    type: String,
    required:true  
},
city_id: {
    type: String,
    required:true
},
location_id: {
    type: String,
    required:true
},
country_name: {

    type: String,
    required:true
   }

  })

  module.exports = mongoose.model("LocationsModel", locationSchema, "locations")

控制器 > location.js

const { status } = require('express/lib/response')
const Locations = require('../Model/location')

 exports.getAllLocations = (req, res) => {
   Locations.find().then(
    result => {

        res.status(200).json({ message: "data fetched successfully", data: result })
    }
).catch(error => {

    res.send(500).json({ message: "Error in Database", error: error })
  })
}

和我的路线

zomato.js

const express = require('express')
const Router = express.Router();
const RestaurantController = require('../Controller/Restaurant')
const LocationsController = require('../Controller/Location')

  // configure routes

    // Restaurants routes
  Router.get('/restaurants', RestaurantController.getAllRestaurants)


  Router.post('/restaurants/filter/:pageNo', RestaurantController.getRestaurantsByFilter)


  // Locations routes

  Router.get('/locations', LocationsController.getAllLocations)

  module.exports = Router

我的 Json 文件 location.json 是这样的:

[
{
    "_id": "1",
    "name": "ShalimarBhagh, Delhi",
    "city_id": "1",
    "location_id": "1",
    "country_name": "India"
},
{
    "_id": "2",
    "name": "Janpat, Delhi",
    "city_id": "1",
    "location_id": "2",
    "country_name": "India"
},
{
    "_id": "3",
    "name": "MSP, Delhi",
    "city_id": "1",
    "location_id": "3",
    "country_name": "India"
}
]

** 更新:我忘了提到我最近更新到 windows10 以确保我的 react 应用程序正常工作,在出现这个问题之后,现在我创建了一个新的应用程序,删除了 mongo 并重新安装了 mongodb 仍然让我出现这个错误邮递员错误:读取 ECONNRESET**

更新我得到了这个堆栈跟踪

C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb- 
 mongoose\node_modules\mongoose\lib\connection.js:797
 const serverSelectionError = new ServerSelectionError();
                           ^
    MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
  at NativeConnection.Connection.openUri 
 (C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb- 
  umongoose\node_modules\mongoose\lib\connection.js:797:32)

【问题讨论】:

    标签: javascript node.js mongodb express mongoose-schema


    【解决方案1】:

    试试这个:

    // imports
    const express = require('express')
    const bodyParser = require('body-parser')
    const cors = require('cors')
    const { append } = require('express/lib/response')
    const zomatoRoutes = require('./Routes/zomato')
    const mongoose = require('mongoose')
    
     // create express server
     const app = express()
    
     // Middleware routes
     app.use(cors())
     app.use(bodyParser.json())
     app.use('/zomato', zomatoRoutes)
    
     //connect mongodb   
     mongoose.connect('mongodb://localhost/zomato', () => {
       console.log("MongoDB Connected");
       const server = app.listen(7878, () => {
          console.log('app running on port 7878');
       })
      server.setTimeout(0) // disable the default time out server mechanism
      },
      e => console.log(e)
     ) 
    

    这是:

    • 初始化exprress应用程序
    • 注册中间件
    • 连接到 mongo
    • 如果连接成功(并且只有这样)- 启动应用程序

    另外,替换您的代码

    res.status(200).json({ data: 'whatever' })
    

    到:

    res.status(200).send({ data: 'whatever' })
    

    您的响应有可能没有返回给客户端,因此 - 导致超时错误。这种方法也应该解决这个问题

    希望它能帮助您解决问题

    【讨论】:

    • 谢谢你的帮助兄弟。但是有问题。我最近更新到 Windows 10。在那之后它不起作用我创建了一个新的新应用程序,它在 Postman 中出现错误:错误:读取 ECONNRESET
    【解决方案2】:

    Localhost 未解析,尽管我使用 mongod --ipv6 将 mongodb 更改为 ipv6,但它仍然不接受,并且在堆栈跟踪中显示 isIPV6 : false。

    所以最后我不得不更改使用答案here 使用 ipv4 监听端口

    //connect to mongoDB
     const uri = 'mongodb://localhost:27017/zomato';
    
     const options = {
     useNewUrlParser: true,
     useUnifiedTopology: true,
     family:4
     }
    
     const connectWithDB = () => {
     mongoose.connect(uri, options, (err, db) => {
      if (err) console.error(err);
      else console.log("database connection")
    })
    }
    
     connectWithDB()
    

    它现在正在工作并获取数据,但想解决 ipv6 nodejs 的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 2016-02-06
      • 2017-08-18
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多