I have a mongo model like this:-
var mongoose = require('mongoose');
const itemsModel = new mongoose.Schema({
_id: {
type: String,
},
userName: {
type: String,
required: true
},
description: {
type: String,
required: false
},
itemId: {
type: String,
required: true,
unique: true
}
});
module.exports = mongoose.model("itemsModel", itemsModel);
and I am handling my backend route in a file called itemRoute.js
like this:-
const express = require("express");
const router = express.Router();
const id = require('uuid');
const itemsModel = require("../src/model/itemsModel");
router.post('/add-item/', (req, res) => {
const { userName, description, itemId } = req.body;
itemsModel.findOne({
itemId: itemId,
userName: userName,
}, (error, prevData) => {
if(error){
return res.send({
success: false,
description: `Internal Server Error ${error}`
});
}
if (prevData.length > 0){
itemsModel.findOneAndUpdate(
{ _id: prevData[0]._id },
{ description: description },
(error, status) => {
if (error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
} else {
return res.status(200).json({
success: true,
description: "Updated item successfully",
prevData: prevData,
status: status
});
}
}
);
}
const newModel = new itemsModel;
newModel._id = id.v4();
newModel.userName = userName;
newModel.itemId = itemId;
newModel.description = description;
newModel.save((error, user) => {
if(error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
}
return res.status(200).json({
success: true,
description: "Added item to db",
user: user
});
});
});
});
router.get('/get-items/:itemId/', (req, res) => {
console.log(req.body);
const itemId = req.params.itemId;
return res.status(200).json({
success: true,
description: "Nicee",
id: itemId,
});
});
module.exports = router;```
I have the following in my index.js
express file:-
app.use('/api', require('./routes/itemRoute'));
and I am calling from my frontend like this:-
handleAddItemButton = (event) => {
event.preventDefault();
const data = {
userName: this.props.userName,
description: this.state.description,
itemId: this.props.itemId,
}
fetch(`http://localhost:8000/api/add-item/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch((err) => console.log(err));
};
My index.js
file:-
/* jshint esversion:6 */
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('./build'));
app.use(express.static('./build/static'));
app.use('/api', require('./routes/auth'));
app.use('/api', require('./routes/items'));
app.use('/api', require('./routes/itemRoute'));
mongoose.set('useCreateIndex', true);
const port = 8000
mongoose.connect('mongodb://localhost:27017/item-app', {
useNewUrlParser: true
})
app.get('/*', (req, res) => {
res.sendFile(path.resolve('./build/index.html'))
})
app.listen(port, () => console.log(`server running at ${port}`));
When my frontend actually makes the request, I am thrown the following error:-
POST http://localhost:8000/api/add-item/ net::ERR_CONNECTION_REFUSED
I have looked through my code again and again but to no avail. Any and all help is sincerely appreciated. Please guide me through what Im doing wrong.
Edit 1:-
After @ewokx comment I ran mongod and got the following;-
Is this the issue? How to solve this?
2
Answers
Hi so I seem to have successfully solved the problem. The problem wasn't with any of the things like db permissions, mongod, ports or something like that. I reset my
index.js
file to match the db name in the db connection. Another thing I was doing wrong, I was passing a json stringified object as the request body. Removing that and on connecting proeprly to the db, the code started working nicely.MongoDB requires a data folder to store its files.
The default location for the MongoDB data directory is
c:datadb
. So, create this folder it will solve your issue.