node js express mongoose api save operation not working - node.js

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;

Related

How can I make an entry to MongoDB with this app?

Between my app and Postman I should be able to make an entry into MongoDB, but I get this.
TypeError: Cannot read property 'title' of undefined
This is the app.js file
const express = require('express');
const app = express();
const Mongoose = require('mongoose');
require('dotenv/config')
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute)
app.use('/posts', () => {
console.log('This is a middleware.')
})
app.get('/', (req, res) => {
res.send('We are at home')
})
//Connect to DB
Mongoose.connect(process.env.DB_CONNECTION)
.then(() => {
console.log('connected to DB')
})
.catch(err => {
console.log(err);
});
app.listen(3000);
This is the posts.js file
const express = require('express');
const router = express.Router();
const Post = require('../models/Post')
var fs = require('fs');
router.get('/', (req, res) => {
res.send('We are at posts')
})
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({message: err });
})
});
module.exports = router;
This file is the Mongoose Schema
const { json } = require('body-parser');
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: JSON,
required: true
},
description: {
type: JSON,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
Then I'm trying to post to MongoDB, through the app with Postman
Hopefully this photo should suffice.
The app is running fine locally on port 3000 and I do believe I am connecting to the database. It seems like a format problem. I don't know if the schema needs to be in JSON somehow or a configuration of Postman needs to change, but I have tried every Postman setting and tried changing the schema to JSON. I also had the type in the Mongoose file as type: String
Add this in app.js for POST Request...
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Add that middleware on top of your routes.

Why am I getting an error like this even after linking all the required dependencies?

index.js
const express = require("express");
const app = express();
const cors = require("cors");
const db = require("./models");
app.use(express.json());
app.use(cors());
//Router
const userrouter = require("./routes/user");
app.use("./user", userrouter);
db.sequelize.sync().then(() => {
app.listen(3001, () => {
console.log("Hello I am server.");
});
});
user.js
const express = require("express");
const router = express.Router();
const { Users } = require("../models");
router.get("/", async (req, res) => {
const noOfUsers = await Users.fetchAll();
res.json(noOfUsers);
});
router.post("/", async (req, res) => {
const post = req.body;
await Users.create(post);
res.json(post);
});
module.exports = router;
users.js
module.exports = (sequelize,DataTypes)=>{
const user = sequelize.define("Users",{
name:{
type:DataTypes.STRING,
allowNull: false,
},
description:{
type: DataTypes.STRING,
allowNull: true,
},
phone:{
type: DataTypes.INTEGER,
allowNull: false,
},
});
return user;
};
I have users.js in models folder. Why am I getting Cannot GET/ when I run the server? I am using node.js and I have also installed cors, mysql2, sequelize and express.
If you look at your index.js file, you're using app.use("./user", userrouter); but it should be app.use("/user", userrouter);.

Post request isn't working in node.js express/mongoose

I have a route to create a category and when I try to run it in postman it returns an error saying, "Cannot POST /api/category"
I have tried to run through my code again and again but I cannot see where is the problem.
Thank for your help in advance
My schema:
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
categoryName: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Categories = mongoose.model("category", CategorySchema);
My route:
const express = require("express");
const router = express.Router();
const auth = require("../../middleware/auth");
const { check, validationResult } = require("express-validator");
const Category = require("../../models/Category");
// #route POST api/category
// #desc Create or update users category
// #access Private
router.post(
"/",
[auth, [check("categoryName", "Category name is required").not().isEmpty()]],
async (req, res) => {
console.log(categoryName);
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
}
);
module.exports = router;
this is the way my code is organized
Ok thanks to Molda I found the problem.
I was missing my route definition in my server.js file.
All good now, thank you for your help.
const express = require("express");
const connectDB = require("./config/db");
const app = express();
//Connect DB
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send("API Running"));
// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/category", require("./routes/api/category"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Hi, I am getting error while making a POST request

I am using Nodejs, MongoDB and Mongoose and while making a POST request I am getting error:
POST http://localhost:3000/subscribers
Content-Type: application/json
{
"name": "Lucky",
"subscribedToChannel": "Dev Tech"
}
Error: {
"message": "Subscriber validation failed: name: Path name is required., subscribedToChannel: Path subscribedToChannel is required."
}
The code snippet is mentioned below:
server.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
mongoose.connect(mongodb://localhost/subscribers, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const subscribersRouter = require('./routes/subscribers')
app.use('/subscribers', subscribersRouter)
app.listen(3000, () => console.log('Server Started'))```
---------------------------------------------------------------------------------------------------
routers/subscribers.js
const express = require('express')
const router = express.Router()
const Subscriber = require('../models/subscriber')
// Creating one
router.post('/', async (req, res) => {
const subscriber = new Subscriber({
name: req.body.name,
subscribedToChannel: req.body.subscribedToChannel
})
try {
const newSubscriber = await subscriber.save()
res.status(201).json(newSubscriber)
} catch (err) {
res.status(400).json({ message: err.message })
}
})
module.exports = router
----------------------------------------------------------------------------------------------------
models/subscriber.js
const mongoose = require('mongoose')
const subscriberSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
subscribedToChannel: {
type: String,
required: true
},
subscribeDate: {
type: Date,
required: true,
default: Date.now
}
})
module.exports = mongoose.model('Subscriber', subscriberSchema)
[1]: https://i.stack.imgur.com/rHf38.jpg
Use bodyParser above app.use(express.json())
Like : app.use(bodyparser.urlencoded({ extended : false }))

post.save is not working (Node/Express/MongoDB)

I am new to node and creating api.
I am able to pass a json in request body and log it on console ,but problem is arising when I am trying to add this data to my database .
I am trying to add data to DB(cloud:Atlas) but post.save is not running .
This is my post.model.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)
This is controller (posts.js)
const express = require('express')
const router = express.Router()
const Posts = require('../model/posts.model')
router.get('/', (req, res) => res.send('We are on posts page'))
router.get('/specific', (req, res) => res.send('We are on specific post page'))
router.post('/', async (req, res) => {
const post = new Posts({
title: req.body.title,
description: req.body.description
})
// try{
// const savedPost = await this.post.save()
// res.json(savedPost)
// }
// catch(arr){
// res
// }
console.log('before save');
post.save().then(data => {
console.log("in then");
res.json(data)
})
.catch(err => {
console.log('in catch');
res.json({ message: err })
})
})
module.exports = router
This is my app.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const bodyParser =require('body-parser')
require('dotenv/config')
//Import Routes
const postsRoutes = require('./routes/posts')
//Middelware
app.use(bodyParser.json())//to be used before app.use(<routes>)
app.use('/posts', postsRoutes)
//app.use(express.bodyParser())
//ROUTES
app.get('/', (req, res) => res.send('We are on home page'))
app.get('/posts', (req, res) => res.send('WE are on posts page '))
//Connect to DB
mongoose.connect('DB_CONNECTION', { useNewUrlParser: true }, () => console.log('Connected to db'))
//how to start listening to the server
app.listen(3000)
Console
This is the req body:
Also when will collections form in my database?
Will it happen when I add first entry of data?
You aren't connected to your monogodb. You have to add the ip address and the name of the database.
In case there is not database with this name, it's going to create a new one.
mongoose.connect('mongodb://localhost/myDB', {
useNewUrlParser: true
});

Resources