节点服务器代码陷入无限循环

时间:2015-01-07 02:10:16

标签: javascript node.js mongodb express mongoose

我已经在我的节点服务器上设置了以下代码,以便根据通过API在GET请求中发送到Instagram的参数(纬度,经度,距离,max_timestamp)来填充数据库中的事件对象。我的代码正确地从我的数据库中提取第一个事件,但在第一个console.log语句中陷入无限循环。

我看到了: sending request to Instagram for New Years Eve - Times Square with max_timestamp: 1419984000在几秒钟内登录我的控制台几十次。我不确定为什么我的其余代码没有运行。

// modules =================================================
var express        = require('express.io');
var app            = express();
var port           = process.env.PORT || 6060;
var io             = require('socket.io').listen(app.listen(port));
var request        = require('request');
var Instagram      = require('instagram-node-lib');
var mongoose       = require('mongoose');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var db             = require('./config/db');
var Event          = require('./app/models/event');

// configuration ===========================================
mongoose.connect(db.url); // connect to our mongoDB database

// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse         application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-  urlencoded

app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method- Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location  /public/img will be /img for users


var baseUrl = 'https://api.instagram.com/v1/media/search?lat=';
var clientId = MY-CLIENT-ID;

Event.find({}, function(err, events) {

  events.forEach(function(event) {

    var name = event.event;
    var latitude = event.latitude;
    var longitude = event.longitude;
    var distance = event.radius;
    var maxTimestamp = Math.floor(new Date(event.start).getTime()/1000);
    var endTimestamp = Math.floor(new Date(event.end).getTime()/1000);


  while (maxTimestamp < Math.floor(Date.now() / 1000) && maxTimestamp < endTimestamp) {
    console.log('sending request to Instagram for ' + name + ' with max_timestamp: ' + maxTimestamp);
    request(baseUrl + latitude + '&lng=' + longitude + '&distance=' + distance + '&max_timestamp=' + maxTimestamp + '&client_id=' + clientId,
      function (error, response, body) {
        if (error) { 
          console.log('error');
          return;
        }

          //JSON object with set of images
          var images = JSON.parse(body.data);
          var numImages = images.length;
          console.log(numImages + ' images returned with starting time ' + images[0].created_time + ' and ending time ' + images[(numImages - 1)].created_time);

            for (var i = 0; i < numImages; i++) {

              //Save the new photo to DB
              Event.findOneAndUpdate( {latitude: latitude}, { $push: {'photos':
                { img: images[i].images.standard_resolution.url,
                  link: images[i].link,
                  username: images[i].user.username,
                  profile: images[i].user.profile_picture,
                  text: images[i].caption ? images[i].caption.text : '',
                  longitude: images[i].location.longitude,
                  latitude: images[i].location.latitude
                }}},
                { safe: true, upsert: false },
                function(err, model) {
                  console.log(err);
                }
              );
              console.log(numImages + ' images saved to db');
            }
            maxTimestamp = images[(numImages - 1)].created_time;
            console.log('max_timestamp incremented to: ' + maxTimestamp);
          }
        );
      }    
    });  
});

// routes ==================================================
require('./app/routes')(app); // configure routes

// start app ===============================================
console.log('Magic happens on port ' + port);
exports = module.exports = app;                         // expose app

0 个答案:

没有答案
相关问题