0
votes

i am new in programmaing. I have connected with MongoDB Atlas, and need to save one object,using POSTMAN.

But i get this message socket hang up. I tried what ever was possible using proxy options.

Please note that i do not have anything saved in my new database. apart from username and password, i am keeling dbname as is. thougt it would create a database named "dbname" itself upon connection. not sure what to do here as well.

DB_CONNECT=mongodb+srv://username:@cluster0.uxjdg.mongodb.net/?retryWrites=true&w=majority

Here are the details

Index.js

const express=require('express');
const app =express();
const mongoose=require('mongoose');
const dotenv=require('dotenv');
const bodyParser=require('body-parser');

dotenv.config();

//Connect to DB
mongoose.connect('process.env.DB_CONNECT',
//{ useUnifiedTopology: true },
{ useNewUrlParser: true },

()=>console.log('connect to db'));

//Middleware
app.use(express.json());

//Import Routes

const authRoute=require('./routes/auth');

//Route Middlewares

app.use('/api/user', authRoute);

app.listen(3000, ()=>console.log('Server up and Running'));

Router

const router=require('express').Router();

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

router.post('/register', async(req, res)=>{

    const user =new User({
        name:req.body.name,
        email:req.body.email,
        password:req.body.password
    });

    try{
     const savedUser=await user.save();
     res.send(savedUser);

    }catch(err){
        res.status(400).send(err);
    }
});



module.exports=router;

Schema


const mongoose=require('mongoose');

const userSchema =new mongoose.Schema({
  name:{

    type:String,
    required:true,
    min:6,
  },
  email:{

    type:String,
    required:true,
    max:255,
    min:6
  },

  password:{

    type:String,
    required:true,
    max:1024,
    min:6
  },

  date:{

    type:Date,
    default:Date.now
  }

});

module.exports=mongoose.model('User', userSchema);
1
Can we see the full text of the error?Joe
Joe, this is the only message socket hang up. This is when i kept the content length of header ON, otherwise it give 400 syntax error. I checked the code and pasted here, seems ok to mesal abb
Does it behave the same if the callback is not async?Joe
Joe without async .this is what i get:sal abb
Error: CORS request rejected: localhost:3000/api/user/registersal abb

1 Answers

0
votes

I had the same exact problem as yours so I thought I'd share the steps that I took to solve this:

  • Go back to your MongoDB project folder
  • Delete the current cluster and create a new cluster
  • You'll obviously have to reconfigure your database access.
  • and I am not sure if this is necessary but I temporarily set the network access to "ALLOW ALL ACCESS FROM ANYWHERE"
  • Reconnect to your cluster i.e. update your DB_CONNECT URL unless your using the same PW.
  • Restart your node as well.

Welp! I hope this helps. Happy coding!