Question

I'm having trouble bootstrapping data on the initial page load.

A quick summary: I've got an express server interacting with MongoDB through mongoose. All of these parts work well. The server serves the index page fine, which runs with a lot of Backbone scripts. The index page runs fine, and Backbone is able to fetch data from the server through the API. All of that works well.

I'm trying to set it up such the server makes a quick call to MongoDB and bootstraps on fifty or so model instances. Here's route for the index page call:

var professorModel = require('../data/models/prof');

module.exports = function (app) {

  app.get('/', function (request, response) {

    professorModel.find().limit(50).exec(function (error, docs) {

    // Also tried: .find().lean().exec(function .... )
    // Also tried: docs = JSON.stringify(docs) ... (with a JSON.parse() on the other end). 
    // Also tried: docs.forEach(function (e, i, a) { newDocs.push(e.toJSON())})...

    response.render('index', { bootstrap : docs });

  });

};

On the index page, it's just <script> var bootstrap = {{{bootstrap}}}; </script>.

It loads the data each time, but it's the browser that has a hard time parsing it. I get 'parse error ILLEGAL', unexpected tokens, etc. But to reiterate: it has to be a formatting thing.

In the express docs, it notes that response.send() is smart about what it sends, and automatically encodes objects as json. Is the problem here that response.render() is not doing so? I feel like there should be an easy solution here.

Thanks

Sam

Was it helpful?

Solution

As it worked out, it was a problem on the client-side.

Previously, my code had been: var bootstrap = {{{bootstrap}}};.

The bootstrap variable here isn't being received as a string: it's being received as an object. Putting the variable between single quotes solved the issue:

var bootstrap = '{{{bootstrap}}}';

There's still a mysterious limit on the length of the string: past 150 or so objects, the JSON parse fails-on-load. Otherwise: works great.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top