jeudi 26 mars 2015

mongoose.js Model.remove only works once within a loop


I'm not sure if this is just my noviceness to asynchronous programming or an actual bug, but whenever I put Model.remove in a loop, it will only work on the first time and then not remove anymore.


My goal is to just have one document in the collection after the function is run, so if there is different way to do that, that would great to know as well.


Here is how my code looks:


(part of server.js)



var schema = new mongoose.Schema({
gifs: [String]
});
var Gifs = mongoose.model('Gifs', schema);

setInterval(function(){

request('http://ift.tt/WEPoqB', function(error, response, html) {

if (!error){
var $ = cheerio.load(html);
$('a.title', '#siteTable').each(function(){
var url = $(this).attr('href');
urls.push(url);
});
}

//remove everything in the collection that matched to {}, which is everything
//then in the callback save the document
//currently know that this will in fact remove all documents within the model
//however, it will only work on its first run
Gifs.remove({},function(error){
console.log('removed all documents');
Gifs.create({gifs: urls}, function(error){
console.log("created new document");
});
});

});
}, 60000);




Aucun commentaire:

Enregistrer un commentaire