The problem is when I make the put request using postman there is an error in my vscode terminal that says:
let product = await Product.findById(req.params.id);
^
TypeError: Cannot read property 'id' of undefined.
I am making this request on postman http://localhost:4500/api/v1/product/61dfc2ba3eb817d287929a7a
(61dfc2ba3eb817d287929a7a is the id) with body as raw json. req.params.id is coming to be undefined..
It seemed like an error in parsing so I added body-parser and cors to it but the same error is being showed up..
Code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
mongoose
.connect("mongodb://localhost:27017/sampl", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("db connected");
})
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number,
});
const Product = new mongoose.model("Product", productSchema);
//create product
app.post("/api/v1/product/new", async (req, res) => {
const product = await Product.create(req.body);
console.log(req.body);
res.status(200).json({
success: true,
product,
});
});
//read product
app.get("/api/v1/products", async (req, res) => {
const products = await Product.find();
res.status(200).json({
success: true,
products,
});
});
//update product
app.put("/api/v1/product/:id", async (res, req) => {
let product = await Product.findById(req.params.id);
product = await Product.findByIdAndUpdate(req.params.id, req.body, {
new: true,
useFindAndModify: false,
runValidators: true,
});
res.status(200).json({
success: true,
product,
});
});
app.listen(4500, () => {
console.log("server is working");
});
The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
So, first we want to pass the req object and then res.
change this
app.put("/api/v1/product/:id", async (res, req) => {
let product = await Product.findById(req.params.id);
to
app.put("/api/v1/product/:id", async (req, res) => {
let product = await Product.findById(req.params.id);
Related
I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.
I have a problem to insert a API call with request in mongodb with mongoose. I am very new in this topic. Need your help!!! Here ist my test.js, how can i solve this problem any ideas. My target is to save the Api call from the url and then update it all 30 min but at the moment i was very happy when i could save the call. For all help i am very grateful.
When i start with node test.js then i get only the ids in mongodb not more.
const request = require('request');
const path = require('path');
const https = require('https');
const mongoose = require('mongoose');
const port = 3000;
const dbUrl = process.env.xxx || 'mongodb://localhost:27017/testingDB';
mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
console.log('Connection ready');
})
.catch((err) => {
console.log(err);
});
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
//Create a Schema
const coinSchema = new mongoose.Schema({
id: String,
coin_id: Number,
name: String,
symbol: String,
market_cap_rank: String,
thumb: String,
small: String,
large: String,
slug: String,
price_btc: Number,
score: Number,
});
//Create a Model with collection coins
const Coin = mongoose.model('Coin', coinSchema);
app.get('/testing', async (req, res) => {
const url = 'https://api.coingecko.com/api/v3/search/trending';
request({ url, json: true }, (error, response) => {
if (error) {
console.log(error);
} else {
Coin.insertMany(response.body.coins);
console.log(response.body.coins);
}
});
});
app.listen(port, () => {
console.log(`Server ready on port ${port}`);
});```
Try
request({ url: 'https://api.coingecko.com/api/v3/search/trending', json: true }, function (error, response, body) {
// ...
Coin.insertMany(body.coins.map(({ item }) => item));
});
I'm writing a code for creating a group within a website. And I'm using MongoDB as my database, but as a beginner, it's hard for me to understand the API that they provide. So basically, I'm having issues with connecting the backend to the frontend when I'm trying to create a group for my website. This is the backend code for create_group
router.post('/create_group', (req, res) => {
try {
const newGroup = Group.create(req.body);
res.status(201).json({
data: {
Groups:
newGroup
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
//res.json(database.groups[database.groups.length-1]);
As you can see, I want to write a code that's appropriate for MongoDB that looks like the portion that I commented out. I want to return the object that I just saved so I can display that information in when I change the route. The frontend code looks like this:
onSubmitCreate = () => {
fetch('http://localhost:3000/groups/create_group', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
members: 1,
likes: 0
})
})
.then(response => response.json())
.then(group => {
if (group) {
//this.props.loadUser(user);
console.log('this is what Im working on' + group.name);
this.props.onCreateGroup(group);
}
});
}
In the frontend, as I make a request to post the information to the database, I want to read the response and work with that information. But when I console.log the group variable, I just get an empty object as a response and I don't know how to make it return the information that the user typed in. And in case you want to see what onCreateGroup fucntion looks like, here it is.
const onCreateGroup = (group) => {
setGroupInfo({
name: group.name,
description: group.description,
likes: 0,
members: 1
});
setRoute('group_page');
}
Please help me! Thank you in advance!
Edit: I was requested to post js file where I import express so I'm posting it here
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://teamboogle:wMKsYJNhTfL89k9#cluster0.nhcrc.mongodb.net/TalkWithMe?retryWrites=true&w=majority", { useNewUrlParser: true });
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const profileRouter = require('./routes/profile');
const postsRouter = require('./routes/posts');
const groupsRouter = require('./routes/groups');
const signinRouter = require('./routes/signin');
const registerRouter = require('./routes/signin');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/profile', profileRouter);
app.use('/posts', postsRouter);
app.use('/groups', groupsRouter);
app.use('/signin', signinRouter);
app.use('/register', registerRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function(){
console.log('Connection Secured');
})
module.exports = app;
You are not saving the object in MongoDB properly, and you also need to return the object that you saved in Group collection as well.
Also, since you are returning data.Groups.group, you need to read that in the response as well
Please try this:
router.post('/create_group', async (req, res) => {
try {
const newGroup = new Group(req.body);
let group = await newGroup.save()
res.status(201).json({
data: {
Groups:
group//return the saved object
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
}
In frontend code
onSubmitCreate = () => {
fetch(...)
.then(response => response.json())
.then(data => {
// read data.Groups.group from response
let group = data.Groups.group
if (group) {
//this.props.loadUser(user);
console.log('this is what Im working on' + group.name);
this.props.onCreateGroup(group);
}
});
}
I am trying to pass data to a MongoDB collection and it returns Cannot POST /courseweb/course/add
Before passing values through axios I tried postman (a google extension) to send data.
This is my server.js which is implemented with expressjs
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");
const InstructorDB = require('./public/DBModels/InstructorDB');
const router = express.Router();
const bundler = new Bundler("./src/index.html");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));
app.use("/courseweb", router);
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Connected to MongoDB via 27017");
});
app.listen(3000, err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log("Application is running on port 3000");
});
app.get("/", function(req, res) {
res.sendFile("./dist/index.html");
});
router.route('/course/add').post((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
router.route('/courses').get((req, res) => {
// name of the course database model here
InstructorDB.find().count(function(err, count){
res.status(200).send(count);
});
});
And this is my InstructorDB.js which is a schema model by mongoose
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
let InstructorDB = new Schema({
firstName: String,
lastName: String,
designation: String,
faculty: String,
contactNumber: Number,
email: String,
password: String,
isEnabaled: Boolean,
courses: [{courseID: String}]
});
module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');
And this is a screenshot and the response I get when I pass the values through postman. I have set header as content-type and application/json too
Can anyone tell me where I have gone wrong?
Make sure you send the right data via your post request and change the verb to post :
app.post('/course/add', (req, res) => {
if(req.body == null){
return res.status(400).send({message: 'bad request'});
}
let instructorDB = new InstructorDB(req.body);
instructorDB.save((err ,doc ) => {
if(err){
res.status(400).send({message: err});
}
res.status(200).send(`Added`);
});
});
You don't need router if you're going to put it in the same file.
try this syntax instead:
app.post('/coureweb/course/add',((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
}));
then take out
app.use("/courseweb")
I am trying to learn REST API. I created POST method but it is not working
get method is working fine in postman but post method is not working. Can anyone help me where I am missing?
I am stuck in it.
here is my code
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//connect to mongoose
Genre =require('./models/genre');
Book =require('./models/book');
// Connect to Mongoose
mongoose.connect('mongodb://localhost/bookstore',{ useNewUrlParser: true });
var db = mongoose.connection;
app.get('/', (req, res) => {
res.send('Please use /api/book or /api/genres');
});
app.get('/api/genres', (req, res) => {
Genre.getGenres((err, genres) => {
if(err){
throw err;
}
res.json(genres);
});
});
app.post('/api/genres', (req, res) => {
var genre = req.body;
Genre.addGenre(genre, (err, genre) => {
if(err){
throw err;
console.log(err);
}
res.json(genre);
});
});
app.listen(3000);
console.log("running on port 3000..");
models/genre.js
const mongoose = require('mongoose');
// Genre Schema
const genreSchema = mongoose.Schema({
name:{
type: String,
required: true
},
create_date:{
type: Date,
default: Date.now
}
});
const Genre = module.exports = mongoose.model('Genre', genreSchema);
// Get Genres
module.exports.getGenres = (callback /* we can access through routes*/, limit) => {
Genre.find(callback).limit(limit);
}
//add genre
module.exports.addGenre = (genre, callback) => {
Genre.create(genre, callback);
}
get method is working fine in postman but post method is not working. Can anyone help me where I am missing?
You need to update your code accordingly:
Add in app.js:
// BodyParser middleware
const BodyParser = require(`body-parser`);
// Create application/json parser
App.use(BodyParser.json({ limit: `50mb` })); // Set request size
// create application/x-www-form-urlencoded parser
App.use(BodyParser.urlencoded({ limit: `50mb`, extended: true }));
Update API call:
app.post('/api/genres', (req, res) => {
var genre = req.body;
Genre.addGenre(genre, (err, genreDB) => {
if(err){
throw err;
console.log(err);
}
res.status(200).send(genreDB);
});
});
Hope this works for you.
If you want to access req.body in your POST handler, you'll need to use some express middleware to actually parse the request body. For example, for parsing JSON bodies, you'll need express.json middleware.