express,routing,mongoose , Select Mongoose Model Based on Express Route

Select Mongoose Model Based on Express Route


Tag: express,routing,mongoose

I think this might be a basic question, but looking for the best approach.

I'm building an express app that should route to one of four different Mongoose models depending on the route.

Something like this:

app.get('/:trial', function(req, res){
    var trial = req.params.trial;
    trial.find(function(err, records) {
        if (err)

        res.json(records); // returns all trial records in JSON format

I have 4 mongoose models named: trial1, trial2, trial3, trial4. I would like the trial parameter of the URL to determine which collection gets queried. Obviously the above won't work, but what should I do instead of rewriting the route four times instead?

Thanks in advance!


You can get models by name:

var mongoose = require('mongoose');

app.get('/:trial', function(req, res){
    var trial = req.params.trial;
    mongoose.Model(trial).find(function(err, records) {
        if (err) {
            // Return when we end the response here...
            return res.send(err);
        res.json(records); // returns all trial records in JSON format

Depending on circumstances, I would validate the value of trial first (so requesting /User doesn't dump all users to the client, for instance).


Express.js server with Apache Tomcat

I am making a sample web application in node.js using express.js. I am getting a little confused when using apache-tomcat as my web server. I have two doubts: When i run apache-tomcat as a web server and my express.js server is providing me services at port number 4000, how does...

My POST from html does not return any value, nodejs, express

I am trying to do a simple post from html page and when I check the console after the post it returns nothing. I have the body parser used correctly on the server side. Is there something that I am doing wrong? var http = require('http'); var fs = require('fs');...

Route parameter with slash “/” in URL,routing,,,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...

Design pattern as alternative to front-end template locals

I am relatively new to web development and am trying to figure out how to publish the server environment (dev, test, prod, etc) to the front-end. I am using Node.js with Express, but the following code is closer to pseudo-code because is this is more of a design pattern question....

Using middleware to call an Authentication API using ExpressJS

I'm using two Node.js + Express applications: Backend Authentication And my front-end is built in AngularJS Basically I'm trying to send a json web token with every request to the Backend, and then use a route middleware to call the Authentication API. It validates that token and add user data...

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

WebApi Routing not working for Post

My WebApiConfig has following routes // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Employee", action = "Get", id = RouteParameter.Optional } ); The Post WebApi method has got following Signatures [HttpPost] public IHttpActionResult Post(Employee emp) { ..... } When i try to call...

Express get error

I am setting up routes to my application controller on a node server - var http = require('http'); var app = require('express')(); app.get('/<path>/<query type>', function(req, res) { //Expecting query parameter <query type>?name=<something> var query =; var path = '/<path>/<query type>?name='+query; var options = { host: 'localhost', port: 8080, path:...

What is wrong with Nodejs?

I am using multer to handle upload image. app.use(multer({ dest: './public/photos', rename: function (fieldname, filename) { return; }, onFileUploadStart: function (file) { console.log(file.originalname + ' is starting ...') }, onFileUploadComplete: function (file) { console.log(file.fieldname + ' uploaded to ' + file.path) //a='asass'; done=true; } }));'/api/photo',function(req,res){ if(done==true){ //ERROR here...

Write NodeJS stream into a string synchronously

I know that one can synchronously read a file in NodeJS like this: var fs = require('fs'); var content = fs.readFileSync('myfilename'); console.log(content); I am instead interested in being able to read the contents from a stream into a string synchronously. Thoughts?... client does not connect to server

I am trying to make a Node.js app that will have an embedded chat. I am using to create that chat. I have attempted to set up my server / client, but the client does not seem to be connecting. I have my application to set log when sockets...

Passing data from server/app.js to controller Angular-fullstack + multer

I'm struggling to get a filename passed from server/app.js to a controller in client/app/ I am using Multer to deal with the file upload which is working fine but i need to pass the filename back to the client to display it in the next view. Here is the code...

Full stack javascript routing explanation needed

I've scaffolded a full stack Mongo, Express, Angular, Node app using yeoman with the Angular Fullstack generator It has created a server/app.js file, which executes a routes.js to handle resources being served by the express server. The meat of routes.js looks like this: // Insert routes below app.use('/api/things', require('./api/thing')); app.use('/api/users',...

Node Server - Source Code accessible

I noticed that when i navigate to localhost:8080/server.js (where my server.js is the server-expressjs obviously) the code of my server is shown in the browser! Even, if i upload the application to openshift, i get the same result (you can test it): Is this a security issue? How...

Redirect user to previous page after authentication

I'm using Google auth through Passport in my app and I'm attempting to redirect the user back to the original page they requested after successful sign-in. I think that location.reload() may be the problem, but not sure how to solve it. routes.js:'/auth/google/return', passport.authenticate('google'), function(req, res) { res.redirect(req.session.returnTo); req.session.returnTo =...

Redis: Delete user token by email ( find Key by Value )

I have followed tutorial on how to create token-based authentication with node from this tutorial I got it all worked out, but I got 1 problem. The way I store token is : KEY = TOKEN VALUE = UserData (Username, email, etc.) To protect multiple devices login, I would...

zip and download from nodejs

I am trying to zip the file and download from server using easy-zip module. But now I can write into a server using following code but how can i make it downloadable??? var app = require('express')(); var easyzip = require('easy-zip'); app.get('/api/downloadFile',function(req,res){ console.log("inside req"); var data = "<html><body><h1>Inside new Html</h1></body></html>"; var...

How to handle one express route different than all other

I'm currently using the Express router within a NodeJS application. I have simply been using app.use(app.router); for routing and it works well. However, I'm now testing out some new routes and want to handle them differently. Ideally I would like to be able to say: var vers2Router = require('./routes/version2'); app.use('/version2',...

res.send and res.render calls

I am trying to determine if i can call res.send(data) and then res.render('reports') simultaneously. To explain further in detail, when i route to '/reports', first on my server side i making a REST call to an API which returns back json data. Now i want this json data to be...

NodeJS for a JAVA developer - Few Questions

I'm working on a project that is heavily based on json. Since 90% of the server side in JAVA would be POJO.toJSON() I decided to give NodeJS a shot! Most of my questions are related to the fact that NodeJS runs as a single thread. Am I right? :) NodeJS...

How to handle expressjs middleware request. post request remains pending made by dropzone

I am using dropzone to upload the file. On the server side I am using node and expressjs. I am also using multer as the file handling middleware. dropzone makes a call to one endpoint to save the file on the server. On the server side, I created an endpoint...

Refactoring Express Routing

I have many express routes doing similar functionality, with the exception of the .put which handles specific functionality. What would be the best way to refactor this type of code. Require Statements var Ale = require('../models/alert-model.js'); var Service = require('../models/services-model.js'); Routes router.route('/ale/:_id') .get(function(req, res) { Ale.findById(req.params._id, function(err, result) { if...

How to create a MySQL schema when deploying with Heroku (Express Server)

Suppose I have the following server.js file: server.js var express = require('express'); var app = express(); var mysql = require('mysql'); var dbhelpers = require('./public/database_helpers.js') var bodyParser = require('body-parser') app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/public/views')); app.use(express.static(__dirname + '/public/controlers')); app.use(express.static(__dirname + '/public/lib')); app.use(bodyParser()) var connection = mysql.createConnection({ **Correct info** });...

$StateProvider Remove Child View Nesting

I am new to angular ui routing . I am creating a sample application and want to display parent and child view separately . I mean when parent item gets selected child view will be displayed and parent view would be hidden . If I add ui-view to parent view...

Emitting and receiving socket io within the same file

I want to do something where I can set up a route to a link like /visit using app.get('/visit', function(req, res){}) etc. And inside that, I want to emit a message like socket.emit("event", "a message") and then inside my io.on("connection") function, be able to listen for event and return the...

NodeJS / ExpressJS check valid token parameter before routing

I have the following app code: (app.js) var express = require('express') , app = express() , port = process.env.PORT || 8082 app.use(require('./controllers')) app.use(function(req, res, next) { res.send('Test') next() }) app.listen(port, function() { console.log('Listening on port ' + port) }) and two controllers: (index.js) var express = require('express') , router =...

Is express similar to grunt? what is the difference? what are the advantages of express over grunt?

I've been working on node,grunt,bower and yeoman from couple of months. I came across MEAN stack applications, in which expressjs is providing the server environment(my understanding). Are both grunt and express similar? Requesting for some helpful link on express and MEAN stack. ...

Rails routing link to specific show

This question seems a little basic, but considering I have 'pages#show' with a show page with url 'history'. How could I add this specific show page to a link: = link_to 'History', pages_path(@?????) PD1: I would prefer avoid using :id since I tend to seed a lot of data, and...

Get local json file using request-promise

I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags: Error: <title>Invalid URI "../testJSON/user.json"</title> I believe my pathing is correct, so am unsure why it's an invalid URI. I've also provided the entire project...

Send code via post message is not working

I wanted to send code to some node application and I use the postman with post message and in the body I put the following: module.exports = function() { var express = require('express'), app = express(); app.set('port', process.env.PORT || 3000); return app; } in the header of the request I...

How to use passport.js's TwitterStrategy sessionless?

I tried to implement TwitterStrategy like it's done with Facebook in: Token based, sessionless auth using express and passport But express still wants me to use session middleware: {"message":"OAuthStrategy requires session support. Did you forget app.use(express.session(...))?" Can someone provide a detailed example? ...

Dropzone.js status is pending and not uploading a file

I am using Multer in back-end to handle file upload and Dropzone.js in front-end. Everything is fine when I use Postman to test my back-end code, but in when I use Dropzone the status is pending and file not getting uploaded. Then after 4 minutes of waiting I get Timeout...

Is there a way to fire an event every time an ajax call in made in AngularJS?

What I'm trying to do is every time a call to the backend is made, I want a spinner to load up with a dark overlay. I know I can do this by simply running the spinner before the call is made, but I'm working with multiple developers and I...

unable to add property to the json object

I am trying to add status to a response on successful update but I am not able to add the status property to json object of form. Here is my code'/forms/update', function(req, res){ if( !== 'undefined' &&{ var condition = {'_id'}; Form.findOneAndUpdate(condition, req.body, {upsert:true}, function(err, form){ if (err)...

Select Mongoose Model Based on Express Route

I think this might be a basic question, but looking for the best approach. I'm building an express app that should route to one of four different Mongoose models depending on the route. Something like this: app.get('/:trial', function(req, res){ var trial = req.params.trial; trial.find(function(err, records) { if (err) res.send(err); res.json(records);...

Symfony/Twig how to render a Route set by anotation?

Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

Secure file upload directly to s3 or server to s3 (from iOS app) [closed]

I need to upload sensitive images to s3 from an iOS app. I'm wondering which option is better: Upload to my server first, then upload to s3. Upload to s3 directly, then upload metadata to my server. ...

Comparison Express JS, Angular JS vs Backbone JS [closed]

I am starting to learn node js for a while and it seem amazing. When I start to apply nodejs to build a scalable website, I am wondering to do Express for back-end, BackBone Js or Angular JS for front-end, people said Express JS is very fast, while Backbone.js seem...

express.js 4: catch bodyParser error in router's errorHandler

How can I catch a bodyParser error in a router's errorHandler in express.js 4? Example code: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // use bodyParser.json() app.use(bodyParser.json()); // setup route /test var testRouter = express.Router();'/', function(req, res, next) { next(new Error('not implemented')); }); testRouter.use('/',...

Angular $routeProvider and Controller As Syntax

Can anyone tell me if it is valid to use $routeProvider with Controller as syntax? I am having issues accessing <h1>{{}}</h1> from the controller where resides. angular.module('ucp.kick', ['ngRoute']).config(function($routeProvider, APP_BASE_URL) { return $routeProvider.when(APP_BASE_URL + 'kicks', { reloadOnSearch: false, navitem: true, name: 'Kicks', templateUrl: 'kick/partials/kick.html', controller: 'kick as KickController' }); });...

Angularjs Login authentication redirection getting — Error: Can't set headers after they are sent

Very new to NodeJS/AngularJS. I am having problem getting a login page to redirect to another page once the id and password are verified. Codes in the controller are as follows triggered by the route '/login/check': exports.logincheck = function(req, res) { User.findOne({email:}).exec(function (err,user) { if (!user) { err =...

Open page url in modal on a page (Facebook Photo URLs)

P.S. I am using html5Mode to remove '#' in routing in below scenario Removing the hashtag from AngularJS urls (# symbol) Consider I have two main pages.One is photos where thumbnails are provided and whose url is /someSlug/photos. Other is the url of a single photo '/someSlug/photos/somePhotoId' which shows a...

Confused about nodejs (and the Passport middleware) sessions

Super simple question that I'm having trouble wrapping my head around. When using sessions with nodejs, are the sessions stored in the users browser? Or are the sessions stored on the server? For example, if I'm using the express-session or passport.session(), where are these session cookies stored?...

Why is address undefined in my app?

I have a simple express app: var express = require('express'); var path = require('path'); var app = express(); = app; var index = require('./routes/index'); app.use(express.static(path.join(__dirname,'client/dist/'))); app.get('/', index.get); function start(){ var port = process.env.PORT || 8080; app.listen(port, function(){ console.log('app is running on port: ' + port); }); }; exports.start =...

Error handling when uploading file using multer with expressjs

I am using multer to save the file on server developed through express & nodejs. I am usign following code. var express = require('express'), multer = require('multer') var app = express() app.get('/', function(req, res){ res.send('hello world'); });'/upload',[ multer({ dest: './uploads/'}), function(req, res){ res.status(204).end() }]); app.listen(3000); Multer saves the file...

What is the bin folder in an express application for?

When creating an express application express <App-name> it creates a few folders and files including a bin. What is the bin folder used for exactly?...

How to correctly use Express 4 multiple routers

I'm attempting to use the Express 4 Router to use a different router based on the path. I want all /api/v2/ routes handled by version2, and every other route handled by version1. The below setup serves me all the version1 routes correctly, but seems to ignore version2 as I get...

Stream read returning empty in nodejs

I am using express to create a webservice that will read string data from a stream, and respond to the HTTP POST request with that value. Here is the code for the S3Store.js file that defines the readFileFromS3(.) function: S3Store.js S3Store.prototype.readFileFromS3 = function(filename, callback) { var readConfig = { 'Bucket':...

Passport.js - req.session.passport.user is not showing up

I am using Passport.js with Express - for some reason the req.session.passport.user value is not present, when it should be, as you can see: here is my passport configuration: passport.serializeUser(function (user, done) { console.log(colors.bgRed('serialize user called, user:', user)); done(null, user._id); }); passport.deserializeUser(function (id, done) { console.log(colors.bgRed('deserialize user called, user_id:', id));...