I'm trying to connect to my mongoDB and to save a new user inside.
When I run the express server, the db is connected but the post request doesn't seem to happen.
Can someone check my code and help me find the problem?
**when I send the request on postmam, the postman ends up with: 'could not get response, error:socket hang up'.
I'm attaching my code below:
my server:
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const authRoute = require('./routes/aouth')
dotenv.config();
//conect to db
mongoose.connect(mongodb://localhost/users, { useUnifiedTopology: true, useNewUrlParser: true }, () => console.log("connected!"))
//middleware
app.use(express.json());
//route middleware
app.use('/api/user', authRoute);
app.listen(3000, () => console.log("listening on port 3000!"))
my User.js:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('User', userSchema);
my router (routes/aouth.js) :
router.post('/reg', async(req, res) => {
const user = new User({
password: req.body.password
})
try {
const savedUser = await user.save()
res.status(201).json(savedUser)
} catch (err) {
res.status(400).json({ message: err.message })
}
})
on postman my request is:
POST http://localhost:3000/api/user/reg
{
"password":"1234"
}
hope you guys can help me!!
Thank you!!
At a glance, I noticed that the path imported is wrong.
const authRoute = require('./routes/aouth')
Shouldn't it be?
const authRoute = require('./router/auth')
To be sure that you are connected to the database add the following lines.
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
You have to add this code to your server.
app.use(express.urlencoded({extended: false}))
It will work.
Extending #Daryl Answer, #Shir: As you mentioned routes folder name is correct.
But you have a file named auth.js & in your server file, you are importing aouth.
Please verify, you have correct import filename specified in server file, Else this could be an import path issue.
Related
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.
picture of mongodb compass.
where my passed body data that is name,email,password is saving in mongodb compass
You should instantiate the new instance of User with new and await the Promise after save:
router.post("/", async (req,res)=>{
try {
const user= new User(req.body);
await user.save();
res.send(req.body);
} catch (e) {
res.send('error');
}
})
module.exports = router
I have a mongodb collection with a few examples and I was trying to display them on my get method but it keeps showcasing the Processing, Please wait... buffer screen without outputting any result. I am wondering why it takes so long and does not display even after an hour and more when it displayed quite quickly on my simpler tests before.
This is my Usermodel
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema(
{
username: { type:String,unique:true,required:true},
email:{type:String,unique:true,required: true},
password:{type: String,required:true,},
isAdmin:{type:Boolean,default: false,}, },
{
timestamps: true,
});
const userModel = mongoose.model("users_list",userSchema);
This is the user router
const express = require('express');
const userModel = require('../models/users');
const { model } = require('mongoose');
const router = require("express").Router();
router.get("/getUser",(req,res)=> {
userModel.find({},(err,result)=>{
if(err){
res.json("There is an error");
}
else{
res.json(result);
console.log("got result");
console.log(result);
}
});
res.send("Ok");
});
module.exports = router;
And here is how my index.js where all the routers are called and fixated.
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const userRouter = require('./apis/routers/userRouter');
const cors = require("cors");
dotenv.config();
mongoose
.connect(process.env.MONG_URL)
.then(() => console.log("DB Connection Successful!"))
.catch((err) => {
console.log(err);
});
app.use(cors);
app.use(express.json());
app.use('/api/users',userRouter);
I have given the right MongoDB URL and it is not enclosed in quotation marks or anything from .env
And right here as you can see in the image, the postman keeps doing this
This sending request is unending and doesn't fetch the data at all. How can I resolve this?
So I feel foolish for asking this, and I know there are a ton of related posts on this, but I cannot find anything to work. I'm guessing that it has to do with the index.js since Postman is saying it cannot even connect to the route. I have 2 routes, and the clientRoutes works just fine, postman returns and it shows up on my frontend. However, making any call to the contractRoutes gets me nothing.
I'm trying to pull all 'contracts' subdocs for a single client. I'm new to Express/Mongoose and I'm guessing that I've missed something totally obvious.
index.js
const express = require("express")
const mongoose = require("mongoose")
const cors = require('cors')
const clientRoutes = require("./routes/clientRoutes")
const contractRoutes = require("./routes/contractRoutes")
const bodyParser = require('body-parser');
mongoose
.connect("mongodb+srv://admin:oneterra#cluster0.0cajn.mongodb.net/Octotest?retryWrites=true&w=majority", { useNewUrlParser: true })
.then(() => {
const app = express()
app.use(express.json())
app.use(cors())
app.use(bodyParser.json());
app.use("/api", clientRoutes)
app.use("/api", contractRoutes)
app.listen(5000, () => {
console.log("Server has started")
})
})
client model
const mongoose = require("mongoose")
const schema = mongoose.Schema({
clientId: Number,
firstName: String,
lastName: String,
phone: String,
contracts: [{
contractId: Number,
authNumber: String,
contType: String,
contHours: Number,
contStartDate: Date,
contEndDate: Date
}],
})
module.exports = mongoose.model("Client", schema)
clientRoutes - which works as expected
const express = require("express")
const Client = require("../models/Client.js")
const router = express.Router()
//Client routes
router.get("/clients", async (req, res) => {
const clients = await Client.find()
res.send(clients)
})
router.get("/clients/:clientId", async (req, res) => {
try {
const client = await Client.findOne({ clientId: req.params.clientId })
res.send(client)
} catch {
res.status(404)
res.send({ error: "Client not found"})
}
})
contractRoutes which only brings the error "Cannot GET /api/clients/1/contracts" (1 being the clientId, which has contracts in the db). On clientRoutes, from the first tutorial I used, I did not put '' around ({ clientId : req.params.clientId). In the code below I have it there when I was trying to figure this out, but I get the same result, and again seems to show I'm missing something at the top level.
const express = require("express")
const Client = require("../models/Client")
const router = express.Router()
try{
const client = await Client.findOne({ 'clientId': req.params.clientId })
const contracts = client.contracts;
res.send(contracts)
} catch {
res.status(404)
res.send({error: "Contracts not found"})
}
console.log(contracts)
I've tried using populate
Client.findOne({ 'clientId': req.params.clientId })
.populate('contracts')
.exec(
function(err, client) {
if (err) res.status(500).send(err);
res.json(client.contracts);
}
);
and even if I copy the exact same route for a single client from clientRoutes, but with the contracts endpoint, I get the same error as above
const express = require("express")
const Client = require("../models/Client")
const router = express.Router()
//Client routes
router.get("/clients/:clientId/contracts", async (req, res) => {
try {
const client = await Client.findOne({ clientId: req.params.clientId })
res.send(client)
} catch {
res.status(404)
res.send({ error: "Client not found"})
}
})
Any help is greatly appreciated, I've spent hours running in circles on this and trying every type of different way to make the call. But in dialing it down to even using the same route from clientRoutes but with the contracts endpoint and getting the error, I'm assuming it has to due with the index.js server connection.
So in case anyone comes across this with the same issue, as I put in the comment, express wasn't accepting the 2nd route starting with the same path.
By changing
app.use("/api", clientRoutes)
app.use("/api", contractRoutes)
to
app.use("/api", clientRoutes)
app.use("/api/clients", contractRoutes)
then the route worked fine. I did not see anything in the express docs saying that no path can be designated as the same, but making the change made it work, so there's that.
I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.
//Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
// Posts.js => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./routes/posts");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
UPDATE
Looks like something is wrong with db connection itself. Below is my connection string. I handled the mongoose connection on error and i get the error shown in screen shot.
mongodb://<dbuser>:<dbpassword>#ds023550.mlab.com:23550/roofapp
Just pasted your code here and is working fine for both post and get.
Are you able to complete the GET request?
How is your project structured?
Make sure you are importing the files correctly.
From your commented out file names you have Post.js with capital letter and you are importing posts. It seems that something is wrong in the imports.
Here is a working solution based on the code you've posted.
Files : app.js - Post.js - Router.js
app.js:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
// require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./Router");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
Router.js
const express = require("express");
const Post = require("./Post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values
router.put('/special/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: {email: req.body.email, password: req.body.password}
},
{
new: true,
useFindAndModify: false
},
function(err, updatedData) {
if(err) {
res.send('Error updating');
} else {
res.json(updatedData);
}
});
});
Try rewriting it using async, and make sure your Mongoose schema is correct as well.
So your mongoose model should be a seperate file called 'userModel.js'.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema ({
email: String,
password: String,
});
let User = module.exports = mongoose.model('User', userSchema);
Then in your app.js.
Have:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');
//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection
db.once('open', function() {
console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
console.log(err);
})
//Starting App (on localhost:3000)
app.listen(port, function() {
console.log('Server started on port ' + port);
});
Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:
mongod
This should work, and if its already running you should see a message at the bottom saying:
2019-07-19T12:17:37.716+1000 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.
Note: Before the route, you need to require your model so mongoose can update records for you.
//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){
const id = req.params.id
//Making a user object to parse to the update function
let updatedUser = {}
updatedUser.email = req.body.email
updatedUser.password = req.body.password
await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
if(err){
console.log(err)
}
else {
console.log(updatedData)
//res.redirect or res.send whatever you want to do
}
})
})