0

I am following this tutorial . I want to replicate the same but I am thinking to use Last.fm API in place of TVDB. So I changed the server.js code from https://jsfiddle.net/3a1wbdkr/ to incorporate album.search method https://jsfiddle.net/f6qh2ed4/

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var async = require('async');
var request = require('request');
var xml2js = require('xml2js');
var _ = require('lodash');

var showSchema = new mongoose.Schema({
  _id: Number,
  name: String,
});

var userSchema = new mongoose.Schema({
  name: { type: String, trim: true, required: true },
  email: { type: String, unique: true, lowercase: true, trim: true },
  password: String,
  facebook: {
    id: String,
    email: String
  },
  google: {
    id: String,
    email: String
  }
});


var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);

mongoose.connect('mongodb://sahat:foobar@ds041178.mongolab.com:41178/showtrackrdemo');
var app = express();

app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

app.get('/api/shows', function(req, res, next) {
  var query = Show.find();
  if (req.query.genre) {
    query.where({ genre: req.query.genre });
  } else if (req.query.alphabet) {
    query.where({ name: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
  } else {
    query.limit(12);
  }
  query.exec(function(err, shows) {
    if (err) return next(err);
    res.send(shows);
  });
});



app.get('/api/shows/:id', function(req, res, next) {
  Show.findById(req.params.id, function(err, show) {
    if (err) return next(err);
    res.send(show);
  });
});
app.get('*', function(req, res) {
  res.redirect('/#' + req.originalUrl);
});
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.send(500, { message: err.message });
});

app.post('/api/shows', function (req, res, next) {
  var seriesName = req.body.showName;
  var apiKey = ' 7b3e1e72b5e06503e298ce018c407cc5';
  var parser = xml2js.Parser({
    explicitArray: false,
    normalizeTags: true
  });
//http://ws.audioscrobbler.com/2.0/?method=album.search&album=believe&api_key=7b3e1e72b5e06503e298ce018c407cc5&format=json
  async.waterfall([
    function (callback) {
      request.get('http://ws.audioscrobbler.com/2.0/?method=album.search&album='+ seriesName+'&api_key='+apiKey+'&format=json', function (error, response, body) {
        if (error) return next(error);
        parser.parseString(body, function (err, result) {
          if (!result.results.albummatches.album.name) {
            return res.send(400, { message: req.body.showName + ' was not found.' });
          }
          var seriesId = result.results.albummatches.album.id;
          callback(err, seriesId);
        });
      });
    },
    //http://ws.audioscrobbler.com/2.0/?method=album.search&album=
    function (seriesId, callback) {
      request.get('http://www.goodreads.com/book/show/50?format=xml&key=' + apiKey + function (error, response, body) {
        if (error) return next(error);
        parser.parseString(body, function (err, result) {
          var series = result.Request.results.work[0];
          var show = new Show({
            _id: result.results.albummatches.album.id,
            name:result.results.albummatches.album.name
          });
          callback(err, show);
        });
      });
    },
    function (show, callback) {
      var url = 'http://thetvdb.com/banners/' + show.poster;
      request({ url: url, encoding: null }, function (error, response, body) {
        show.poster = 'data:' + response.headers['content-type'] + ';base64,' + body.toString('base64');
        callback(error, show);
      });
    }
  ], function (err, show) {
    if (err) return next(err);
    show.save(function (err) {
      if (err) {
        if (err.code == 11000) {
          return res.send(409, { message: show.name + ' already exists.' });
        }
        return next(err);
      }
      var alertDate = Date.create('Next ' + show.airsDayOfWeek + ' at ' + show.airsTime).rewind({ hour: 2});
      agenda.schedule(alertDate, 'send email alert', show.name).repeatEvery('1 week');
      res.send(200);
    });
  });
});

But whenever I add any album name I get TypeError: Cannot read property 'results' of undefined at /home/karan/work/showapp/server.js:94:22 I have changed the database schema also. I don't understand what's causing the problem. Is the API call not constructed properly ?

mr-karan
  • 203
  • 4
  • 11
  • Do not add 3 pages of code. Include only relevant parts. – Salvador Dali Apr 08 '15 at 22:03
  • The error is pointing to the last value before a `.results` [property access](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) because the `undefined` value cannot have properties. So, either `result` (for `result.results`) or `result.Request` (for `result.Request.results`) is `undefined`. Given how much of the results from the API seem to lowercase, best guess is `result.Request` should be `result.request`. Though, you should also be checking for `err`s. – Jonathan Lonowski Apr 08 '15 at 22:09
  • error here too -> `request.get('http://www.goodreads.com/book/show/50?format=xml&key=' + apiKey + function (error, response, body)`. You're concatenating a function onto the request url – lyjackal Apr 08 '15 at 22:13

0 Answers0