mongoose MongoDB post from API endpoint buffering在10000ms后超时

pdsfdshx  于 2023-04-30  发布在  Go
关注(0)|答案(1)|浏览(171)

我使用MongoDB创建了一个简单的用户创建,并从端点发布。
在Postman中提交json数据的帖子会导致500内部服务器错误和终端中的MongooseError: Operation users.findOne() buffering timed out after 10000ms
index.js

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const usersRouter = require('./routes/users')
require('dotenv').config()

const app = express()

app.use(express.json())
app.use(cors({
  origin: 'http://localhost:3000',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

// Connect to DB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const connection = mongoose.connection
connection.once('open', () => {
  console.log("MongoDB database connection established successfully")
})

// Use the user router middleware
app.use('/users', usersRouter);

// Start the server
const port = process.env.PORT || 5000
app.listen(port, () => {
  console.log(`Server is running on port: ${port}`)
})

app.js

const express = require('express');
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Require the users route
const usersRouter = require('./routes/users');

// Use the users router as middleware with a base URL of /api/users
app.use('/api/users', usersRouter);

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

routes/users.js

const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');

router.post('/register', userController.registerUser);

module.exports = router;

controllers/userController.js

const User = require('../models/User');

// Create user
const registerUser = async (req, res) => {
    try {
        const { name, email, password } = req.body;
        // Check if user with the provided email already exists
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return res.status(400).json({ message: 'User with this email already exists' });
        }
        // Create new user document
        const user = new User({ name, email, password });
        await user.save();
        res.status(201).json({ message: 'User registered successfully', user });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
}

module.exports = {
    registerUser
}

models/User.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String
  },
  email: {
    type: String
  },
  password: {
    type: String
  }
});

const User = mongoose.model('User', userSchema);
module.exports = User;

然后在Postman中我只是在http://localhost:3000/api/users/register上做一个简单的帖子

{
    "name": "John New",
    "email": "john.new@example.com",
    "password": "password123"
}

任何建议都是有帮助的,我觉得我在兜圈子,错过了一些明显的东西。谢谢。

dly7yett

dly7yett1#

这是由于以下教程的疏忽而修复的。我愚蠢地运行索引。js和app.js,这是完全不必要的。只有索引。js需要运行,因为它连接到Mongo,然后我的端点需要在postman中更改。
然后成功!

相关问题