Reputation: 574
I'm trying to learn the MERN stack. I'm creating my first very simple site. Now, I created a route where I create an user, using the datas passed throw body. Here is the code of the server:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors);
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser:true });
const connection = mongoose.connection;
connection.once('open', () =>{
console.log("MongoDB database connection established succesfully")
})
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
Now, here is the code of the users router file, into i put the code:
const router = require('express').Router();//setting it as a express router
let User = require('../models/user.model');//requise the model created before
router.route('/').get((req, res) => {
User.find()//mongoose method, returns a promise
.then(users => res.json(users))//return the list of user
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
And, in the end, here is the model user schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//create the schema for the user
//like the model in Flask
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
},{
timestamps:true,
});
const User = mongoose.model('User', userSchema); //create the model, via the schema
module.exports = User;
Now, to test if it is correct, before implement other code and the frontend, I would like to test it out. First I would like to add a new user, to see if the API works properly. I'm using postman. I sent the request on this URL: http://127.0.0.1:5000/users/add
, with the following json in the body:{"username": "name"}
. Then I send, but Postman continue to say me that it is sending the request, and it continues for minutes. I can't understand if the problem is the promise, that is too low, if I wrote something incorrectly in the code or in the test configuration, if there are issues with the Mongo database, or anything else. Can you help me please? Thanks
Upvotes: 1
Views: 500
Reputation: 289
in your DB connection you are not waiting for the promise
to be resolved
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
app.use(cors());
app.use(express.json());
const port = process.env.PORT || 5000;
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.ATLAS_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (err) {
console.error(`Error: ${err.message}`);
process.exit(1);
}
};
connectDB()
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
Upvotes: 1