node.js - Mongoose callback not working using Forever -
i trying run background process forever adds data external service mongodb database every hour (i new node , had no idea how this). using node express , running forever task using
forever -o out.log -e err.log start background/collector.js
so have feedback process. code following:
var request = require('request'); var mongoose = require('mongoose'); var model = require('../models/model.js'); // starting collector process addnewdata(); function addnewdata() { request('external_service_url', function (error, response, body) { if (!error && response.statuscode == 200) { var models = json.parse(body); console.log('adding new models...') for(var = 0; < models.length; i++) { console.log(i); model.create(models[i], function (error, post, result) { console.log('test'); if (error) console.log('something went wrong adding document!'); if ( ! result.updatedexisting) { console.log('a new document has been added!'); } }); } console.log('models added: ' + models.length); // every hour collect new data console.log('waiting hour...'); settimeout(addnewdata, 36000000); } }) }
i don't know why seems .create()
callback not working, console.logs placed inside create callback not showing in logs. forever not work mongoose? have idea?
well here's thing. never "connected" mongoose adapter database. fixed adding:
mongoose.connect('mongodb://myhost/mydatabase');
somewhere near top before attempt else. won't "connect" in order, mongoose methods work out. "asynchronous programming", read on rest.
also should not looping since not waiting "callback" ( it's not closure it's callback ) complete or otherwise "throttle" connection, can lead problems.
use "async" instead handle this. in example .eachlimit()
in order limit number of parallel operations reasonabe level:
async.eachlimit(models,10,function(el,callback) { model.create(models[i], function (error, result) { // maybe call callback(err); // signal done }); },function(err) { // comes here on completion or error });
remember "asychronous" code needs execute on "callbacks" or "promises" in order signal when things done. unline in "scynchronous" programming each next line executes when previous lines of code complete.
your "for" loop otherwise "sends everything" server , not wait completion before continuing execution.
but main problem here connection. still should fix rest shown.
Comments
Post a Comment