Mongodb 在 nodejs 上连接,本地主机不断重新加载
Mongodb connected on nodejs and localhost keeps on reloading
我正在尝试使用 nodejs express 脚本连接到我的后端 mongodb 5.0.5。
当 运行 使用 nodemon 连接 app.js 时,它显示你的 mongodb 已连接,但在本地主机上它继续重新加载,没有任何错误堆栈跟踪。
我在模型中使用 mongoose 模型,就像在 nodejs 中的 MVC 中一样。不知道为什么它没有在本地主机上获得 运行,上次我使用这些文件时它工作正常。
这是我的文件:
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 个文件
locations.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)
试试这个:
// 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' })
有可能您的响应没有返回给客户端,因此导致超时错误。这种方法也应该解决这个问题
希望对您有所帮助
Localhost 未解析,虽然我使用 mongod 将我的 mongodb 更改为 ipv6 --ipv6 仍然不接受并且在堆栈跟踪中显示 isIPV6 : false.
所以最后我不得不更改使用答案 here listen to port using 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 的问题。
我正在尝试使用 nodejs express 脚本连接到我的后端 mongodb 5.0.5。 当 运行 使用 nodemon 连接 app.js 时,它显示你的 mongodb 已连接,但在本地主机上它继续重新加载,没有任何错误堆栈跟踪。
我在模型中使用 mongoose 模型,就像在 nodejs 中的 MVC 中一样。不知道为什么它没有在本地主机上获得 运行,上次我使用这些文件时它工作正常。
这是我的文件:
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 个文件 locations.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)
试试这个:
// 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' })
有可能您的响应没有返回给客户端,因此导致超时错误。这种方法也应该解决这个问题
希望对您有所帮助
Localhost 未解析,虽然我使用 mongod 将我的 mongodb 更改为 ipv6 --ipv6 仍然不接受并且在堆栈跟踪中显示 isIPV6 : false.
所以最后我不得不更改使用答案 here listen to port using 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 的问题。