PUT and DELETE - RESTful API Express MongoDB Mongoose - node.js

First time posting. I'm building a blog site and using Node.js, Express.js, MongoDB, and Mongoose for my back-end. GET and POST work for getting and creating posts. However, PUT and DELETE are not working when using POSTMAN as I get "Cannot DELETE(PUT) /api/blog". I feel like it's related to routes, particularly when I'm trying to findById (/api/blog/:blog_id).
Server.js
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var logger = require('morgan');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
mongoose.connect('mongodb://127.0.0.1:27017/blog');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function callback () {
console.log("Scrolls are ready to be written!!!");
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.text());
app.use(methodOverride());
app.use(express.static(__dirname + '/client'));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, HEAD, DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, content-type, Accept');
next();
});
// *Routes*
require('./app/routes.js')(app);
// *App Start*
// http://localhost:8080
app.listen(port);
console.log('Connected to port ' + port);
exports = module.exports = app;
app/routes.js
var Blog = require('./models/blog');
module.exports = function(app) {
// *Server Routes*
// Place API calls here
// Place Authentication routes here
//var express = require('express');
//var router = express.Router();
// *API Routes*
// Uses Mongoose to GET all Blog Posts from database
app.get('/api/blog', function(req, res, next) {
Blog.find(function(err, blog) {
// If error
if (err) return next(err);
//res.send(err);
res.json(blog);
});
});
// Uses Mongoose to POST new Blog Posts in database
app.post('/api/blog', function(req, res) {
Blog.create({
title: req.body.title,
body: req.body.body,
author: req.body.author,
comments: req.body.comments,
likes: req.body.likes,
dislikes: req.body.dislikes,
image: req.body.image,
createdOn: req.body.createdOn
}, function(err, blog) {
if (err)
res.send(err);
Blog.find(function(err, blog) {
if (err)
res.send(err)
res.json({ message: 'Blog Post Created!' });
});
});
});
// Uses Mongoose to GET Blog Post by _id from database
app.get('/blog/:blog_id', function(req, res) {
Blog.findById(req.params.blog_id, function(err, blog) {
if (err)
res.send (err);
res.json(blog);
});
})
// Uses Mongoose to PUT updates for Blog Posts by _id in database
app.put('/blog/:blog_id', function(req, res) {
Blog.findById(req.params.blog_id, function (err, blog) {
if (err) res.send(err);
if (req.body.title) blog.title = req.body.title;
if (req.body.body) blog.body = req.body.body;
if (req.body.author) blog.author = req.body.author;
if (req.body.comments) blog.comments = req.body.comments;
if (req.body.likes) blog.likes = req.body.likes;
if (req.body.dislikes) blog.dislikes = req.body.dislikes;
if (req.body.image) blog.image = req.body.image;
if (req.body.createdOn) blog.createdOn = req.body.createdOn;
blog.save( function (err) {
if (err) send (err);
res.json({message: 'Blog Post Updated!'});
});
});
});
// Uses Mongoose to DELETE Blog Posts by _id in database
app.delete('/blog/:blog_id', function(req, res) {
Blog.remove({
_id: req.params.blog_id
}, function (err, blog) {
if (err) return res.send(err);
res.json({ message: 'Blog Post Deleted'});
});
});
// API's for PUT, POST, DELETE go here
// *Frontend Routes*
// Route to handle all AngularJS requests
app.get('*', function(req, res) {
res.sendfile('./client/views/index.html');
});
};

Related

'Post' request not updating the data and giving error in NodeJS

I am a newbie to NodeJS. I am trying to make a simple API relating to a bookstore.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
app.use(bodyParser.json());
Genre = require('./models/genre.js');
Book = require('./models/book.js');
mongoose.connect('mongodb://localhost/bookstore');
const db = mongoose.connection;
app.post('/api/genres', function(req, res) {
const genre = req.body;
Genre.addGenre(genre, function(err, genre) {
if(err) {
throw err;
}
res.json(genre);
});
});
app.listen(3000);
console.log('Running on port 3000...');
Here is the genres.js
var mongoose = require('mongoose');
const genreSchema = mongoose.Schema({
name:{
type: String ,
required: true
},
create_date:{
type: Date,
default: Date.now
}
});
const Genre = module.exports = mongoose.model('Genre', genreSchema);
//Add Genre
module.exports.addGenre = function(genre, callback){
Genre.create(genre, callback);
}
I tried both RestEasy and Postman. Get request is successful but nothing on Post request. It gives this error in the IDE when I make a request.
ValidationError: Genre validation failed: name: Path name is
required.
Also, when I check on MongoShell it does not create date for books and genres.
Alright, I tried it out and your code does work for me, so it probably was just CORS-problems after all.
This is how I made my test request:
<html>
<head><script src="https://unpkg.com/axios/dist/axios.min.js"></script></head>
<body>
<script>
axios
.post('http://localhost:3000/api/genres', { name: "my genre" })
.then(response => {
document.body.innerHTML =
`<pre>${JSON.stringify(response.data, null, 4)}</pre>`;
});
</script>
</body>
</html>
This calls the request from localhost:80 and CORS-headers are needed if you request from another port. Still, I got big errors in my console:
Failed to load http://localhost:3000/api/genres: Request header field
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
Meaning I missed a CORS-header I thought we didn't need. Sorry about that, updated headers:
app.use((req,res,next)=>{
res.header("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Language, Content-Type");
res.header("Access-Control-Allow-Origin", "*");
next();
});
And here is the complete code just to be thorough, including serving my index.html:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const path = require("path");
app.use(bodyParser.json());
Genre = require("./genre.js");
mongoose.connect("mongodb://localhost/bookstore");
const db = mongoose.connection;
app.get("/", function(req, res) {
res.sendFile(path.resolve(__dirname, "index.html"));
});
app.use((req, res, next) => {
res.header("Access-Control-Allow-Headers", "Accept, Accept-Language, Content-Language, Content-Type");
res.header("Access-Control-Allow-Origin", "*");
next();
});
app.post("/api/genres", function(req, res) {
const genre = req.body;
Genre.addGenre(genre, function(err, genre) {
if (err) {
throw err;
}
res.json(genre);
});
});
app.listen(3000);
console.log("Running on port 3000...");
You didn't use the genre inside your req to create
module.exports.addGenre = function(genre, callback){
Genre.create(genre, function (err, gen) {
return callback(err, gen)
})
}

Creating MongoDB connection with mongoose

I am desperately trying to create a connection with mongoDB with the MEAN stack, using mongoose.
My MongoDB instance (mongod) is running and I can use mongo.exe and tested it by inserting some documents, it worked fine. But I have problems to create a connection to MongoDB with mongoose, and inserting a document with the .save() method does not work either...
I first wanted to try my POST method, created a function and tested it by creating some values in POSTMAN. But no documents were inserted in my MongoDB datbase..
This is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require("morgan");
//var routes = require('./routes');
//var cors = require('cors')
//configure app
app.use(morgan('dev')); //log requests to the console
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 5000;
//DATABASE SETUP
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/DNZ'); //connect to uor datbaase
//Handle the connection event
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
//DNZ models live here
var FA = require('./models/DNZmodels/FA');
//ROUTES FOR OUR API
//=============================================================================
//create our router
var router = express.Router();
//middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
console.log('Today is:', Date())
next();
});
//test route to make sure everything is working (accessed at GET http://localhost:5000/DNZ/)
router.get('/', function(req, res) {
res.json({ message: 'Welcome to DNZ API!' });
});
//on routes that end in /FA
//----------------------------------------------------
router.route('/FA')
// create a FA (accessed at POST http://localhost:8080/DNZ/FA)
.post(function(req, res) {
//console.log(req.body);
//console.log(req.body.params);
//res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(req.body));
/*
var timestamp = req.body.Timestamp;
var prognostizierterBetriebswert = req.body.PrognostizierterBetriebswert;
var posFlexPot = req.body.posFlexPot;
var negFlexPot = req.body.negFlexPot;
var leistungsuntergrenze = req.body.Leistungsuntergrenze;
var leistungsobergrenze = req.body.Leistungsobergrenze;
var posGesEnergie = req.body.posGesEnergie;
var negGesEnergie = req.body.negGesEnergie;
var preissignal = req.body.Preissignal;
var dummy1 = req.body.Dummy1;
var dummy2 = req.body.Dummy2;
var dummy3 = req.body.Dummy3;
*/
var fa = new FA();
fa.name = req.body.name;
console.log("Hier erscheint var fa:", fa);
//console.log(Dummy1);
//res.send(JSON.stringify(timestamp));
// create a new instance of the FA model
/*
var fa = new FA({
Timestamp: timestamp,
Leistungsuntergrenze: leistungsuntergrenze,
Leistungsobergrenze:leistungsobergrenze,
PrognostizierterBetriebswert :prognostizierterBetriebswert,
posFlexPot: posFlexPot,
negFlexPot:negFlexPot,
posGesEnergie: posGesEnergie,
negGesEnergie: negGesEnergie,
Preissignal:preissignal,
Dummy1: dummy1,
Dummy2: dummy2,
Dummy3: dummy3
})
*/
//SAVE the new instance
fa.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("debug");
res.status(200);
res.json({ message: 'FA created!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FA.find(function(err, fas) {
if (err)
res.send(err);
res.json(fas);
});
});
//on routes that end in /FA/:FA_id
//----------------------------------------------------
router.route('/FA/:FA_id')
// get the bear with that id
.get(function(req, res) {
FA.findById(req.params.bear_id, function(err, fa) {
if (err)
res.send(err);
res.json(fa);
});
})
// update the bear with this id
.put(function(req, res) {
FA.findById(req.params.FA_id, function(err, fa) {
if (err)
res.send(fa);
//bear.name = req.body.name;
/*
FA.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'FA updated!' });
});
*/
});
})
/*
// delete the bear with this id
.delete(function(req, res) {
FA.remove({
_id: req.params.bear_id
}, function(err, FA) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
*/
//REGISTER OUR ROUTES -------------------------------
app.use('/DNZ', router);
//START THE SERVER
//=============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
/*
// set static directories
app.use(express.static('./dist'));
app.use(cors());
// Define Routes
var index = require('./routes/index');
var users = require('./routes/users');
//Set up routes
routes.init(app)
//run
app.listen(port);*/
console.log('Server started, Listening on port ', port);
I used the "template" from the Bear tutorial:
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
the problem here is already, that there is no message: "DB connection alive". However, in the bear tutorial (whose code I used here), the DB connection is built and I can insert bear documents in the database. However, here it does not work...
and this is my FA Schema model from FA.js:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var FASchema = new Schema({
Timestamp: Date,
PrognostizierterBetriebswert: Number,
posFlexPot: Number,
negFlexPot: Number,
Leistungsuntergrenze: Number,
Leistungsobergrenze: Number,
posGesEnergie: Number,
negGesEnergie: Number,
Preissignal: Number,
Dummy1: Schema.Types.Mixed,
Dummy2: Schema.Types.Mixed,
Dummy3: Schema.Types.Mixed
//same: Dummy: {}
});
//var FASchema = new Schema({name: String});
module.exports = mongoose.model("FA", FASchema, 'FA');
console.log("FA wird ausgeführt!");
Anybody got an idea why there is no DB connection created?
when I test your code , the Error (Can't set headers after they are sent) was thrown. you can delete res.send(JSON.stringify(req.body)); and restart service

How to generate token using passport.js while signing in locally and not with any other social media channel?

I am trying to generate token while logging in locally. Let's say I am normal user and want to sign in. Will token get generated while signing in? and how? Need guidance. Thanks
As I am using mongodb I require my users schema model in my routes code.Here is my routes code user.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/schema');
var Verify = require('./verify');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
When you look at the code you will notice a verify variable.It is nothing but verification that is user is registered or not.If user registered then user will allow for login.After login user will get a successfull response along with token.So here is my veirfy code verify.js
var User=require('../models/schema');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, {
expiresIn: 3600
});
};
exports.verifyOrdinaryUser = function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secretKey, function (err, decoded) {
if (err) {
var err = new Error('You are not authenticated!');
err.status = 401;
return next(err);
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
var err = new Error('No token provided!');
err.status = 403;
return next(err);
}
};
If you observe the code there is a variable like config this is nothing but connection to my mongodb.Here is the code config.js
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/conFusion'
}
And the user schema is here schema.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{
type:String,
required:true,
unique:true
},
email:{
type:String,
required:true,
unique:true
},
phone:{
type:Number,
required:true,
unique:true
},
password:{
type:String
}
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
And finally server code app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var User = require('./models/schema');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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');
});
app.listen(3000,function(){
console.log("Server Listening on 3000");
});
module.exports = app;
project structure must be as per my code
+app.js
+config.js
+routes(directory)
++user.js
++verify.js
+models(directory)
++schema.js
run the code node app.js
When you want to register use http://localhost:3000/users/register
and for login use http://localhost:3000/users/login

How can I do Passport Authentication on multiple users?

Here I have multiple users like Parent,Trainer,Provider.I wrote individual schemas, routes and verify codes for registration and login and for storing, collections also different for each.when I make to run the application it is properly running.And after that I opened the postman tool I registered as" parent" the response is "Registration Successfull" and login as parent I am getting token so that I can perform the functions what a Parent can do in my project.And after that I logout as parent.Next, when I try to registered as Trainer/Provider the response is "Unauthorized". But the fields what I am giving at time of registration are stored in respective collections in database.When I give same values what a parent gave at the time of registration to trainer registration and provider registration then the response is "Registration Successfull" when I give different values other than what a parent gave it shows me "Unauthorized".So, I want to know why this issue arises? And how can I fix this problem?
Here is my schema code
<!-- trainer schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var trainerUser= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
trainerUser.plugin(passportLocalMongoose);
module.exports = mongoose.model('trainerUser', trainerUser);
<!-- parent schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
email:String,
password: String,
phonenumber:Number
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('parentlog', User);
<!-- provider schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
Here is my routes code for each module
//trainer route
<!-- trainer route -->
var express = require('express');
var router = express.Router();
var passport = require('passport');
var trainerUser = require('../models/traineruser');
var Verify = require('./trainerverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
trainerUser.register(new trainerUser({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//parent route
const AuthenticationController = require('../controllers/authentication');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/puser');
var Verify = require('./parentverify');
var mongoose=require('mongoose');
const requireLogin = passport.authenticate('local', { session: false });
router.route('/')
.get(function(req, res) {
User.find({},function(err,users){
if(err) {
return res.status(403).json({
err: 'You are not authorized to perform this operation!'
});
} else {
res.json(users);
}
});
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email:req.body.email,phonenumber:req.body.phonenumber }),
req.body.password, function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', requireLogin, AuthenticationController.login);
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//provider route
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
var Verify= require('./userverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
and app.js code is here
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
<!-- we're connected! -->
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var trainerusers = require('./routes/trainerusers');
var pusers = require('./routes/pusers');
var contacts=require('./routes/contactRouter');
var student=require('./routes/studentRouter');
var batch=require('./routes/batchRouter');
var venue=require('./routes/venueRouter');
var trainerrouter = require('./routes/trainerrouter.js');
var report=require('./routes/reportRouter');
var attendance=require('./routes/attendanceRouter');
var app = express();
<!-- view engine setup -->
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
<!-- uncomment after placing your favicon in /public-->
<!-- app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));-->
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
<!-- passport config -->
var User = require('./models/user');
var trainerUser = require('./models/traineruser');
var Puser = require('./models/puser');
app.use(passport.initialize());
passport.use(new LocalStrategy(Puser.authenticate(),trainerUser.authenticate(),User.authenticate()));
passport.serializeUser(Puser.serializeUser(),trainerUser.serializeUser(),User.serializeUser());
passport.deserializeUser(Puser.deserializeUser(),trainerUser.deserializeUser(),User.deserializeUser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/trainerusers', trainerusers);
app.use('/pusers', pusers);
app.use('/contacts',contacts);
app.use('/student',student);
app.use('/batch',batch);
app.use('/venue',venue);
app.use('/report',report);
app.use('/trainer',trainerrouter);
app.use('/attendance',attendance);
<!-- catch 404 and forward to error handler -->
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
<!-- error handlers -->
<!-- development error handler -->
<!-- will print stacktrace -->
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
<!-- production error handler -->
<!-- no stacktraces leaked to user -->
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;

MEAN stack application - getting details of a single user, querying by username

I have built an API to GET and POST values into a database(MongoDB) using NodeJS and Express.
I am able to get the total list of users stored on my database (localhost:3000/user)
But I want to get a single users details by either entering the userID or userName(localhost:3000/user/:username)(localhost:3000/user/:userID)
I am able to get a single users details through ObjectID(localhost:3000/user/:id)
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var routes = require('./routes/index');
//var users = require('./routes/users');
//Router for developers
var developer = require('./routes/developer');
//Router for TvShows
var tvshow = require('./routes/tvshow');
//Router for TvShows
var user = require('./routes/user');
//Router for TvShowRating
var tvshowrating = require('./routes/tvshowrating');
//Router for TvShowEpisodes
var tvshowepisodes = require('./routes/tvshowepisodes');
//Router for TvShowNewsFeed
var tvshownewsfeed = require('./routes/tvshownewsfeed');
//Router for TvShowSeason
var tvshowseason = require('./routes/tvshowseason');
//Router for TvShowRatingUser
var tvshowratinguser = require('./routes/tvshowratinguser');
// load mongoose package
var mongoose = require('mongoose');
// Use native Node promises
mongoose.Promise = global.Promise;
// connect to MongoDB
//mongoose.connect('<string>')
//mongoose.connect('mongodb://localhost/televisionary-api')
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Registering routers
app.use('/developer', developer);
app.use('/tvshow', tvshow);
app.use('/user', user);
app.use('/tvshowrating', tvshowrating)
app.use('/tvshowepisodes', tvshowepisodes)
app.use('/tvshownewsfeed', tvshownewsfeed)
app.use('/tvshowseason', tvshowseason)
app.use('/tvshowratinguser', tvshowratinguser)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
. routes/User.js
var express = require('express');
var router = express.Router();
var User = require('../models/User.js');
/* GET /user listing. */
router.get('/', function(req, res, next) {
User.find(function (err, user) {
if (err) return next(err);
res.json(user);
});
});
/* POST /user */
router.post('/', function(req, res, next) {
User.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /user/id */
router.get('/:id', function(req, res, next) {
User.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /user/:id */
router.put('/:id', function(req, res, next) {
User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /user/:id */
router.delete('/:id', function(req, res, next) {
User.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
. models/User.js
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
userId:Number,
userName: String,
userEmail: String,
userPassword: String,
userCreatedDateTime: Date,
userWatchList: [
{
watchListItemId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowAddedDateTime: Date
}
],
userFavouriteList: [
{
favouriteId:Number,
tvShowId: Number,
tvShowFavouritedDateTime: Date
}
],
userRatings: [
{
tvShowUserRatingId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowRatedDateTime: Date,
tvShowRating: Number,
tvShowUserTags:[String]
}
]
});
module.exports = mongoose.model('User', userSchema);
If you want to get user details by entering username or userid in one service then modify your service with this:
router.get('/:keyword', function(req, res, next){
User.findOne({$or:[{userName: req.params.keyword}{userId:req.params.keyword}]},
function (err, post) {
if (err) return next(err);
res.json(post);
});
});
You can use findOne method to get a specific user from a database.
router.get('/user/:username', function(req, res, next) {
User.findOne({userName: req.params.username}, function(err, user) {
if(err)
console.log(err);
else
//do something with user
})
});
Same for fetching user using userId.

Resources