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.
Related
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}`));
I've created a very simple API in NodeJs. Here is the code:
const Post = require('../models/article');
...
router.post('/contribute', (req, res) => {
console.log('Pushing new article');
let userPost = req.body;
let post = new Post(userPost);
post.save((error, registeredPost) => {
if (error) {
console.log(error);
} else {
res.status(200).send(registeredPost);
}
})
})
...
module.exports = router;
The structure of a Post is this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
articleid: String,
title: String,
content: String,
date: String,
contributor: String,
upvotes: Number,
upvoters: [String],
downvotes: Number,
downvoters: [String]
})
module.exports = mongoose.model('article', articleSchema, 'articles');
Here is server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes/api');
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
app.use('/api', api);
app.get('/', function(req, res) {
res.send('Server is up and running!');
})
app.listen((3000), function() {
console.log('Server listening on heroku environment port');
});
Ideally the data should come from an angular form/template but before pushing the code I wanted to test this on Postman. Here is the screenshot:
I'm getting:
Cannot POST /contribute
Please point out my mistake.
Because you are using:
app.use('/api', api)
So, make sure to use this endpoint:
localhost:3000/api/contribute
And now, it's will working fine.
I didn't notice that I'm hitting the wrong URL.
Wrong:
localhost:3000/contribute
Correct:
localhost:3000/api/contribute
This is working absolutely fine now and I'm getting correct json response from the server also.
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'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.
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
});