MERN stack, REST api Postman, Cannot GET / - node.js

I'm trying to create a simple REST api using Postman and the MERN stack
I have the following files
server.js, Item.js, items.js, keys.js
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// BodyParser Middleware
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
//Connect to Mongo
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.use('./api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started'));
Item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
items.js
const express = require('express');
const router = express.Router();
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items))
});
module.exports = router;
keys.js
module.exports = {
mongoURI: 'mongodb://tset:tset123#ds241012.mlab.com:41012/mern_shopping'
}
The server connects and connects to the DB - I get the console logs.
In postman if I try the GET and the url http://localhost:5000 I get
Cannot GET /
If I try http://localhost:5000/api/items I get
Cannot GET /api/items

Change this
app.use('./api/items', items);
to
app.use('/api/items', items);

and for http://localhost:5000 , the root you have to define with
app.get('/', function (req, res) {})

Related

I'm unable to add data to MongoDB database

I'm trying to add data in the form of users to my MongoDB database which is in my local drive, but no data is being added according to post requests on postman. I have written an API to handle this post request on userRoute file. Below is the file.
const User = require("../models/userModel");
const express =require("express");
const router = express.Router();
//Fetching all users from the database
router.route("/").get((req,res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json(`There was an error: ${err.message}`));
});
//Adding user to the database
router.route("/add").post((req,res) =>{
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json("User added successfully!!"))
.catch(err => res.status(400).json(`There was an error:${err.message}`))
});
module.exports = router;
Below is also my User schema in the userModel file
const mongoose = require ("mongoose");
const Schema = mongoose.Schema
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 5,
maxlength: 15
}
},
{
timestamps: true
}
)
const User = mongoose.model("User",userSchema);
module.exports = User;
My server file containing the connection to the database and routing
//require the installed packages
const express = require("express");
const cors = require("cors");
const mongoose = require ("mongoose");
const res = require("express/lib/response");
const App = express();
require("dotenv").config();
//middlewares
App.use(cors());
App.use(express.json());
//setting environment variables and explicitly declared variables
const port = process.env.PORT || 3000;
const db = process.env.MONGODB_URI || "mongodb://localhost/tizi";
//routes
const exerciseRoute = require("./routes/exerciseRoute");
const userRoute = require("./routes/userRoute");
//App to use required routes(Use App.set and not App.use)
App.set("/Users",userRoute);
App.set("/Exercises",exerciseRoute);
//setting up server
App.listen(port,() =>{
console.log(`Server is running on port : ${port}`)
});
//connecting to database
mongoose.connect(db,
{
useNewUrlParser:true,
useUnifiedTopology : true
},
(err) => {
err
? console.log(`there is a problem: ${err.message}`)
: console.log("connected to database successfully");
});
//maintaining connection to database
mongoose.connection;
Try to use
await User.create({username});
Instead of save()

Unable to post data to a collection in mongodb database

I am working with mongodb right now for creating an android app using react native.My problem is i am not able to post data to collection in mongodb.
My app.js code
const express = require("express");
const app = express();
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
app.use(cors());
app.options("*", cors());
//middleware
app.use(express.json());
app.use(morgan("tiny"));
//Routes
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const api = process.env.API_URL;
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/users`, usersRoutes);
app.use(`${api}/orders`, ordersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("Database Connection is ready...");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("server is running http://localhost:3000");
});
My categories.js:
const {Category} = require('../models/category');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) =>{
const categoryList = await Category.find();
if(!categoryList) {
res.status(500).json({success: false})
}
res.send(categoryList);
})
router.post('/', async (req,res)=>{
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color
})
category = await category.save();
if(!category)
return res.status(404).send('The category cannot be created!')
res.send(category);
})
module.exports = router;
My category.js:
const mongoose = require('mongoose');
const categorySchema = mongoose.Schema({
name: {
type: String,
required: true,
},
icon: {
type: String,
},
color: {
type: String,
}
})
exports.Category = mongoose.model('Category', categorySchema);
Through postman tool i checked it but there is no error even though i am unable to post the data and in mongodb database it is displaying as Query Results: 0

How do you search for an entry by a specific field like name in a mongodb server using express?

This is an express server that interacts with a mongoDb server using mongoose.Here I want to search for a specific entry with a given name instead of using findbyid function in the /getCollege/:name route.
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// app.use(parser);
mongoose.connect('mongodb+srv://swapnil:abc#cluster0.ma46p.mongodb.net/db?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('connected to db') })
//
app.get('/', (req, res) => {
res.send('We are home');
})
app.get('/getCollege/:name',async (req,res) =>{
})
app.listen(3000);
Parameters variables such as :name are available through req.params, on your case: req.params.name. After getting the value you would something like:
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// your code
app.get('/getCollege/:name',async (req, res) =>{
try {
const document = await College.findOne({ name: req.params.name });
res.json(document);
} catch(error) {
// Handle the error here.
console.log(error);
}
});
// your code
Take a look at these reading materials as well:
1 - http://expressjs.com/en/guide/routing.html
2 - https://medium.com/weekly-webtips/9-best-practices-for-rest-api-design-7fb0b462099b

Unable to store the data from node.js to mongoDB atlas below are the code snippets

I'm Unable to store the data from node.js to mongoDB atlas below are the code snippets.
Below is the app.js code where i established the mongodb connection.
const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
const Post=require("./models/post");
const mongoose=require("mongoose");
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
app.use(cors());
app.post('/sms', function (req, res) {
let obj=JSON.parse(req.body.user);
const user= new Post({
userName:obj.userName,
password:obj.password,
email:obj.email,
address:obj.address
})
user.save()
.then(data => {
res.json(data),
res.status(200).json({data})
})
.catch(err => {
res.json(err)
});
})
mongoose.connect("mongodb+srv://srihari:srihari#cluster0-yuykq.mongodb.net/srihari?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true},()=>{
console.log("DB connected!");
})
app.listen(8080);
Below is the code of Schema to bind the data which is coming from frontend.
const mongoose = require("mongoose");
const postschema=mongoose.Schema({
userName:{
type:String
},
password:{
type:String
},
email:{
type:String
},
address:{
type:String
},
});
module.exports = mongoose.model('Posts',postschema)
Try using Async/Await functions when storing/retrieving data in mongodb;
const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
const Post=require("./models/post");
const mongoose=require("mongoose");
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
app.use(cors());
app.post('/sms', async function (req, res) {
let obj=JSON.parse(req.body.user);
const user= new Post({
userName:obj.userName,
password:obj.password,
email:obj.email,
address:obj.address
})
await user.save()
.then(data => {
res.json(data),
res.status(200).json({data})
})
.catch(err => {
res.json(err)
});
})
mongoose.connect("mongodb+srv://srihari:srihari#cluster0-yuykq.mongodb.net/srihari?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true},()=>{
console.log("DB connected!");
})
app.listen(8080);
It's because you are using Schema directly. First you have to define it like below.
const Schema = mongoose.Schema ;
Write above line of code after you imported the mongoose.

nodejs express route resulting in error 404

The route is not working. I been looking for the cause and I can't find where the problem is. I keep on getting 404 error on postman with the server running.
Here is my server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB Config
const db = require ('./config/keys').mongoURI;
// Connect to Mongo
mongoose.connect(db, {useNewUrlParser: true} )
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
//Routes
app.use ('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Here is the file containing the routes. Is located at /routes/api
const express = require('express');
const router = express.Router();
// Item Model
const Item = require('../../models/Item');
// #route GET api/items
// #desc Get All Items
// #access Public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items));
});
module.exports = router;
File models/item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
404 status : Route Not found , the url you are trying that is not found
in your app js , add slash / before api
app.use('/api/items', items);
url will be :
http://localhost:5000/api/items
Please understand the basic routes first.
Here is https://expressjs.com/en/guide/routing.html
When you run app like that
http://localhost:3000
app is runnin exactly on this url. If you route somthing else like that "api/items" this means that
http://localhost:3000api/items.
So create any route firstly add a '/' and then it looks like
http://localhost:3000/api/items

Resources