Unable to post data to a collection in mongodb database - node.js

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

Related

ValidationError: name: Path `name` is required., tech: Path `tech` is required. In mongoose

is anything I'm doing wrong, I get this error Error ValidationError: name: Path name is required., tech: Path tech is required. while POST the data in postman.
here is my index.js
const express = require('express')
const mongoose = require('mongoose')
const mongoDB = 'mongodb://127.0.0.1:27017/local_library'
const routers = require('../public/app')
const bodyParser = require("body-parser")
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/app', routers)
app.use(bodyParser.json());
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true })
const con = mongoose.connection
con.on('open', () => {
console.log('connected..')
})
app.use(express.json)
app.listen(3000, () => {
console.log('server started')
})
schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const SomeModelSchema = new Schema({
name: {
type: String,
required: true
},
tech: {
type: String,
required: true
},
})
module.exports = mongoose.model('SomeModel', SomeModelSchema )
app.js
const bodyParser = require('body-parser')
const express = require('express')
const router = express.Router()
const SomeModel = require('../models/schema.js')
router.get('/', async(req, res) => {
try{
const receive = await SomeModel.find()
res.json(receive)
}catch(err){
res.send('Error ' + err)
}
})
router.post ('/', async(req, res) => {
const send = new SomeModel({
name: req.body.name,
tech: req.body.tech,
})
try{
const a1 = await send.save()
res.json(a1)
}catch(err){
res.send('Error' + err)
}
})
module.exports = router
You need to select json option from postman body option.
choose type JSON in the your BODY

Node js - mongodb not responding

Need help, I am trying to learn nodejs from youtube. I have created below but not getting any response from browser. Can you please check below code and advise what I have missed??
if I removed the courseModel.find ... from course.js and just write resp.send("XYZ") its showing on browser otherwise nothing is showing. please help
seems something is missing in mangodb connection string
--index.js
const connection = require('./model/connection');
const express = require('express');
const app = express();
const handleBars = require('express-handlebars');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const courseController = require('./controllers/course');
const server = http.createServer(app);
app.use(bodyParser.urlencoded({
extended: true,
}))
app.use("/course", courseController);
server.listen(3900, () => {
console.log("server is in running mode.");
});
--connection.js
const mongoose = require('mongoose');
var conn = mongoose.createConnection("mongodb://localhost:27017/learning", (err) => {
if (!err) {
console.log("Mongo db connected");
} else {
console.log(err);
}
});
const courseModels = require("./course.model");
--course.model.js
const mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
courseName: {
type: String,
required: 'Required'
},
courseId: {
type: String,
},
courseDuration: {
type: String,
}
});
module.exports = mongoose.model("Course", CourseSchema);
--course.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const courseModel = mongoose.model("Course");
router.get("/lists", (req, resp) => {
courseModel.find((err,docs)=>{
if(!err){
resp.send(docs)
}
});
});
module.exports = router;
--logs
issue resolved after updating the connection.js as below
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learning',
{
useNewUrlParser: true,
// useFindAndModify: false,
useUnifiedTopology: true
}, console.log("mongo db connected")
);
Insted of .
server.listen(3900, () => {
console.log("server is in running mode.");
});
use :
app.listen(3900, () => {
console.log("server is in running mode.");
});

node js express mongoose api save operation not working

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;

TypeError: Cannot read property 'username' of undefined in node.JS / express cannot post to route

I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {

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.

Resources