0

data is not saving in mongodb compass . i have used node js to connect to mongodb . a router is also there . model schema is also present .inside thunder client body i have passed a json according to model schema . app listen is working fine and connection to mongodb is also successful . but i could not see those passed data in my mongodb.literally i have tried everything but could not get any solution how to save my data ?

db.js (mongo server)

const mongoose = require('mongoose');

const mongoURI = "mongodb://localhost:27017/"
const connectToMongo = ()=>{
    mongoose.connect(mongoURI, { useNewUrlParser: true,useUnifiedTopology:true },()=>{
        console.log("Connected to Mongo Successfully");
    })
}

module.exports = connectToMongo;

index.js (express and mongo server)

const connectToMongo = require('./db');  //here we import db.js from the above
const express = require('express');

  

connectToMongo();
const app = express();
const port = 3000;


app.use(express.json());

// Available Routes
app.use('/api/auth', require('./routes/auth')) //one route ./api/auth is the route


app.listen(port, () => {
  console.log(`iNotebook backend listening at http://localhost:${port}`)
})

auth router

const express = require("express")
const User = require("../models/User") //User schema described below.
const router = express.Router()

router.get("/",(req,res)=>{
    console.log(req.body)
    const user=User(req.body)
    user.save()
    res.send(req.body)
})
module.exports = router

User schema inside model folder

const mongoose = require('mongoose');
const { Schema } = mongoose;
 
const UserSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    }
  });
  const User = mongoose.model('user', UserSchema);
  module.exports = User;

picture of thunder client

here you can see https://localhost:300/api/auth is the router . in body i have given name ,email,password and response i am getting right . and also it is showing connected to mongo successfully.

here you can see https://localhost:300/api/auth is the router . in body i have given name ,email,password and response i am getting right . and also it is showing connected to mongo successfully. picture of mongodb compass.

where my passed body data that is name,email,password is saving in mongodb compass where my passed body data that is name,email,password is saving in mongodb compass

Rahul Mohanty
  • 342
  • 3
  • 9

1 Answers1

0

Try this in your db.js. Replace localhost:27017 with 127.0.0.1:27017.

const mongoURI = 'mongodb://127.0.0.1:27017/';
user16217248
  • 3,119
  • 19
  • 19
  • 37