Save data to MongoDB using NodeJS - javascript

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")

Related

Unable to access object properties while doing a post request

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.

Getting TypeError: User is not a constructor when testing user add with API

I am trying to make my backend work with MongoDB ATLAS.
I'm using express, mongoose and node.js for my tests and when I am trying to test my API routes (in this case to add a user)
The code I have is the following:
users.js
const router = require('express').Router();
const { Router } = require('express');
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router
user.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
}, {
timestamps: true,
});
const User = mongoose.model('User', userSchema);
module.exports = User;
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
When I am testing this with postman via a POST I get the following error: I am getting the following error: TypeError: User is not a constructor
The post is done to http over port 5000 with raw json body as "username": "blahblahblah"
Can you help with this maybe?
I am not sure what happened but today I cut and pasted back all the code and the API started to work just fine. Now I can add users without any problems.
Could be a glitch but not sure at this point.

Having Issues with Writing Backend Code in Express and Connecting To React

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);
}
});
}

Cannot POST to CosmosDB using Angular

I am trying to post to my cosmosDB using Angular. I can GET just fine, but POST returns with a 404 error in Postman. I am new to routes and APIs so I am a little lost on what is causing the issue.
Here is my index.js
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes');
const root = './';
const port = process.env.PORT || '3000';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(root, 'dist/checkin')));
app.use('/api', routes);
app.get('*', (req, res) => {
res.sendFile('dist/checkin/index.html', {root});
});
app.listen(port, () => console.log(`API running on localhost:${port}`));
My routes.js
const contactService = require('./contact.service');
const router = express.Router();
router.get('/contacts', (req, res) => {
contactService.getContacts(req, res);
});
router.post('/contact/', (req, res) => {
contactService.postContact(req, res);
});
module.exports=router;
My contact.service.js which contains all of my operations (Just GET and POST right now)
const ReadPreference = require('mongodb').ReadPreference;
require('./mongo').connect();
function getContacts(req, res) {
const docquery = Contact.find({}).read(ReadPreference.NEAREST);
docquery
.exec()
.then(contacts => {
res.status(200).json(contacts);
})
.catch(error => {
res.status(500).send(error);
return;
});
}
function postContact(req, res) {
const originalContact = { uid: req.body.uid, name: req.body.name, description: req.body.description };
const contact = new Contact(originalContact);
contact.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json(contact);
console.log('Contact created successfully!');
});
}
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
module.exports = {
getContacts,
postContact
};
Input is obtained through an HTML forum which is picked up and sent through
return this.http.post<Contact>(`${api}/contact/`, contact);
}

How to call POST method in express js?

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.

Categories