Skip to content

Instantly share code, notes, and snippets.

@jvadillo jvadillo/routes.js
Last active Jun 22, 2017

What would you like to do?
Express + Node.js + Mongodb: get parametter attribute list and search by $in operator
var express = require('express');
var router = express.Router();
* Get events from the REST webservice
* [GET] url:,gallery,show
router.get('/event', function(req, res) {
var query = {}; //query for MongoDB
var arr,subq;
var eventType;
if (req.query.eventType) {
eventType = req.query.eventType; //get value of eventType param from the request object.
//Transform tCSV received to Array
subq = {};
subq["$in"] = [];
arr = eventType.split(',');
//Create subquery
subq["$in"] = arr;
//Add the subquery to the query object
query["eventType"]= subq;
//Get the DB and then the collection:
var db = req.db;
var collection = db.collection('events');
//Find and return the response.
collection.find(query).toArray(function(err, docs) {
if( err || !docs) {
console.log("No events found");
res.end("No events found for: "+query);
else {
res.json({ events: docs });
module.exports = router;
* A simple Nodejs and Express server using MongoDB.
var http = require('http');
var path = require('path');
var cors = require('cors');
var bodyParser = require('body-parser');
var express = require('express');
//DB init (MongoDB)
var db = {};
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://myhost:27017/mydatabase';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, thisdb) {
db = thisdb;
assert.equal(null, err);
console.log("Connected successfully to server");
var app = express(); //Creates an Express application
var server = http.createServer(app); //calls http.Server() internally and returns the resulting instance.
//Express configuration:
app.use(express.static(path.resolve(__dirname, 'client')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Make our db accessible to our router
req.db = db;
var events = require('./routes/events');
app.use('/', events)
//Bind and listen for connections on the given host and port
server.listen(process.env.PORT || 3000, process.env.IP || "", function(){
var addr = server.address();
console.log("Swingnow server listening at", addr.address + ":" + addr.port);
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.