First request to node.js app on Windows Azure with MongoDB yields 400 Bad Request First request to node.js app on Windows Azure with MongoDB yields 400 Bad Request azure azure

First request to node.js app on Windows Azure with MongoDB yields 400 Bad Request


In order to guarantee access to any connection in node.js, you have to put all code that requires a connection inside of the callback. The way that mongoose exposes this connection is through an event. When the event 'open' is called by the mongoose connection, then you have access to a database connection.

I.E.

mongoose.connect('details');mongoose.on('open', function () {  var connection = mongoose.connection;  // Do things with your connection here  doThings(connection);});function doThings(connection) {  app.get(...);}


It would be helpful if you had a code snippet, but my guess is that your connection to mongo is happening asynchronously and your site is serving the request before the connection is actually open.

I tested this scenario and couldn't reproduce the issue. You can see my code here: https://github.com/ntotten/azure-mongo-sample

Basically, I am using mongoose to connect and the connection is happening right away when the app is loaded. You can see the code below.

app.js:

/** * Module dependencies. */var express = require('express')  , routes = require('./routes')  , user = require('./routes/user')  , http = require('http')  , path = require('path');var TaskList = require('./routes/tasklist');var taskList = new TaskList(process.env.CUSTOMCONNSTR_MONGOLAB_URI);...

tasklist.js:

var mongoose = require('mongoose')  , task = require('../models/task.js');module.exports = TaskList;function TaskList(connection) {  mongoose.connect(connection);}...