post request not taking in data - express js and mongo - node.js

I am using this code:
app.post("/users", function(req, res) {
db.collection(USERS_COLLECTION).insertOne(req.body , function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new user.");
} else {
res.status(201).json(req.body);
}
});
});
and I am trying putting in this request: localhost:8080/users?firstName=foo&lastName=bar
but when I try the post request in postman it returns just an id and doesn't insert the params in the database.
{
"_id": "584f04eb141faa7df7fc4059"
}
how do I fix this so that it returns the data or do I need to create a schema first and check against it? If I could be pointed in the right direction that would be great

You're correct in that you need a schema!
If there were no schema in a database, you essentially would have a bucket full of (potentially) mismatched JSON objects. Thus, it would be tedious to ensure that your keys match up to their expected values.
If you're new to Mongo, I'd recommend checking out Mongoose ODM. It helps when trying to understand the structure and quirks of a NoSQL DB.

ok.. So I created a Schema
var mongoose = require('mongoose');
// user schema
var usersSchema = mongoose.Schema({
firstName: String,
lastName : String,
email : String
});
mongoose.model('users', usersSchema);
and the post request code looks like this:
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;
var USERS_COLLECTION = "users";
var mongoURL = "the url is here";
var user = require("./Models/User");
var mongoose = require('mongoose');
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect(mongoURL);
// USERS API ROUTES BELOW
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
/* "/USERS"
* POST: creates a new user
*/
app.post("/users", function(req, res) {
var firstName = req.params.firstName;
var lastName = req.params.lastName;
var email = req.params.email;
//call the create function for our database
mongoose.model('users').create({
firstName : firstName,
lastName : lastName,
email : email
}, function (err, user) {
if (err) {
res.send("There was a problem adding the information to the database.");
} else {
//User has been created
console.log('POST creating new users: ' + user + firstName);
res.format({
//JSON response will show the newly created user
json: function(){
res.json(user);
}
});
}
})
});
though the issue is that when I send a http post request :
localhost:8080/users?firstName=foo&lastName=bar&email=foobar#gmail.com
req.body.firstName = undefined and req.params.firstName = undefined how do I get it to properly read in the values? When I put static strings in the place of req.body... it works perfect.
this is what returns in json currently:
{
"__v": 0,
"_id": "5851567048018fa141543f53"
}

21 things matter the most on this problem
you do not implement a body-parser
here you can install it by: npm I body-parser
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
add content type in postman if you use postman to send API
Content-Type: application/JSON

Related

How to Update data from Node.js

I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values
router.put('/special/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: {email: req.body.email, password: req.body.password}
},
{
new: true,
useFindAndModify: false
},
function(err, updatedData) {
if(err) {
res.send('Error updating');
} else {
res.json(updatedData);
}
});
});
Try rewriting it using async, and make sure your Mongoose schema is correct as well.
So your mongoose model should be a seperate file called 'userModel.js'.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema ({
email: String,
password: String,
});
let User = module.exports = mongoose.model('User', userSchema);
Then in your app.js.
Have:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');
//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection
db.once('open', function() {
console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
console.log(err);
})
//Starting App (on localhost:3000)
app.listen(port, function() {
console.log('Server started on port ' + port);
});
Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:
mongod
This should work, and if its already running you should see a message at the bottom saying:
2019-07-19T12:17:37.716+1000 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.
Note: Before the route, you need to require your model so mongoose can update records for you.
//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){
const id = req.params.id
//Making a user object to parse to the update function
let updatedUser = {}
updatedUser.email = req.body.email
updatedUser.password = req.body.password
await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
if(err){
console.log(err)
}
else {
console.log(updatedData)
//res.redirect or res.send whatever you want to do
}
})
})

Unable to check if field exists on MongoDB using NodeJs

I am using NodeJs and MongoDb as a backend service from my android app.I am checking if Phone field exists in my database.
My problem is everytime I check for the field it sends response field exists even if Phone field is not present in document.
Here is my code:
const express = require('express');
const bodyParser = require('body-parser');
const env = require('dotenv').config();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
var dburl = process.env.URL;
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
router.post('/checkPhone',(req,res) => {
var data = req.body.uId;
MongoClient.connect(dburl,{useNewUrlParser:true},(err,client) => {
if(err){
console.log("Error:" +err);
}
else{
var collect = client.db('Bookbudi_db').collection('Users');
collect.find({_id:data,Phone:{$exists:true}},(err,doc) => {
if(err){
console.log("Error:" +err);
}
if(doc){
res.send("Exist");
}
else{
res.send("Doesn't exist");
}
});
}
});
});
module.exports = router;
Someone please let me know what I am doing wrong in above code. Any help would be appreciated.
THANKS
if { $exists:true } returns the document - it means that the field is there.
It is possible that your schema defines this field and initiates it w/ null - note that $exists will still return those fields.
References:
$exists

NodeJS trouble sending messages to client

I am trying to learn Node.JS, but making a REST API using this tutorial:
https://medium.freecodecamp.org/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
I am having a very stupid little issue I can't seem to fix. In my user_routes.js file, I am trying to write several messages to the express() app, however it never works after the first res.send() call. Why is this? I can't find anywhere in my code where I am closing the connection or whatever, so why can't I write more than once to the request?
My user_routes.js
module.exports = function(app, db) {
app.post('/user', function (req,res) {
res.send("User Request Recieved via POST");
// Add the user to the database, if they don't already exist
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const user = {
firstName: firstName,
lastName : lastName,
email : email,
password : password
};
if (db.collection('users').find({'email':email}).count() == 0) {
res.send('Unique Email');
db.collection('users').insert(user, (err, result) => {
if (err) {
console.log("error");
} else {
console.log(result.ops[0])
}
});
} else {
res.send("Email already in use")
}
})
};
Any my server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 6969;
const db = require('./config/db')
// We need to decode data from the url using the body-parser lib
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url).then( function(db) {
require('./app/routes')(app, db);
app.listen(port, () => {
console.log('We are live on ' + port);
});
}).catch (function (err) {
console.log(err);
});
module.exports = app;
I don't seem to close the connection anywhere, so why is it I am only able to write one message to the client?
res.send() is the last thing your function should be doing. Think of it like a return for your function, you can't return multiple times.
res.send() == return()
res.send() is equivalent to "return" for your post -- you can only do it once per call.
Multiple Messages per res.send()
If you want to send multiple messages through one call, you need to compile an object/array of messages you want to send and send that object/array through your res.send(). Example:
ret_msg = [];
ret_msg.push("Here's your first message.");
ret_msg.push("Here's your second message.");
ret_msg.push("Here's your third message.");
res.send(ret_msg);

Not able to update a record in mongodb using mongoose

I am writing an API using mongo express and node and I have two collections as of now 1) users 2) userlist
I am trying to implement change password functionality for the user and want to update the password for the login user.This is my code for the api.
Facing cast to string failed for value error.
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
const port = 4000;
const jwt = require('jsonwebtoken'); //used to create, sign , and verify tokens
const logger = require('morgan');
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/saddleHorseacademy");
//Setting up basic middleware for all express requests
app.use(logger('dev')); //Log requests to API using morgan
//Enabling CORS from the client side
app.use(function (request,response,next) {
response.header("Access-Control-Allow-Origin","*");
response.header('Access-Control-Allow-Methods','PUT ,GET ,POST ,DELETE ,OPTIONS');
response.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
response.header("Access-Control-Allow-Credentials","true");
next();
});
var registerSchema = new mongoose.Schema({
firstName: String,
lastName: String,
address: String,
birthDay: Date,
packageOption: String,
batchOption: String,
startDate: Date,
endDate: Date,
phoneNumber: Number,
emailValue: String,
specialRemarks: String
});
// var changePassword = new mongoose.Schema({
// username : String,
// newPassword : String,
// });
var createUser = new mongoose.Schema({
userName : String,
password : String
});
var students = mongoose.model("students",registerSchema);
var userList = mongoose.model("UserList",createUser);
// var passwordChange = mongoose.model("UserList",changePassword);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", (request,response) =>
{
response.send("hello");
});
// post call for creating user
app.post("/addStudent",(request,response)=>{
var myData = new students(request.body);
myData.save().then(item=>{
response.send('Student successfully registerd');
})
.catch(error =>{
response.status(400).send('Student not successfully registered');
});
});
//updating the password
app.put("/loginPassword",(request,response)=>{
var newPassword = new userList(request.body);
var query = {userName:request.body.userName};
userList.findOneAndUpdate(query,{$set:{password:newPassword}},{new:false},function(error,doc) {
if(error)
{
console.log(error);
response.send("Password not updated");
}
else {
response.send("password updated");
}
})
});
// post call creating user
app.post("/loginPassword",(request,response)=>{
var myUsers = new userList(request.body);
myUsers.save().then(item2=>{
response.send("User Created");
})
.catch(error=>{
response.status(400).send("not able to create user");
});
});
app.listen(port,()=>{
console.log("server listening to port" +port);
})
so what I want is in my create user schema my password should get updated when I call app.put api from the front-end. Please can some-one help by writing the exact query.
When i tried to do findOneandUpdate() then i got cast ti string error. please can any body help . or write the put request. thank's
You created a variable newPassword which is a model object, you are passing it as a string.
Change your query object to:
{$set: {password: request.body.newPassword}}

Can't get users using restful API with node and mongodb

When I set up the route for users in server.js and test with postman/localhost I get the error message, cannot GET /users. Same with any other crud operation. How can I fix this route?
server.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var mongoOp = require("./models/mongo");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
router.get("/",function(req,res){
res.json({"error" : false,"message" : "Hello World"});
});
router.route("/users")
.get(function(req,res){
var response = {};
mongoOp.find({},function(err,data){
// Mongo command to fetch all data from collection.
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
});
app.use('/',router);
app.listen(3000);
console.log("Listening to PORT 3000");
mongo.js
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/meanapi');
var mongoSchema = mongoose.Schema;
var userSchema = {
"userEmail" : String,
"userPassword" : String
};
module.exports = mongoose.model('userLogin', userSchema);
something helpful for these cases is to set NODE_ENV=development as an environment variable and use morgan. It prints out all the requests that hit your nodejs server with status code, method, path etc.
Here's a simple way to set it up:
if ('production' != app.get('env')) {
app.use(morgan('dev'));
}
Another thing that helps in debugging is
app.on('error', function (err) {
console.error(err); // or whatever logger you want to use
});
Ass that after all the middleware and it should print out if some requests fail to get all the way to your handlers.
Hope this helps!

Resources