mongoose.js Model.remove只能在循环中运行一次

时间:2015-03-27 01:07:51

标签: javascript node.js mongodb mongoose

我不确定这只是我对异步编程或实际错误的新手,但每当我将Model.remove放入循环时,它只会在第一次工作,然后不再删除。

我的目标是在函数运行后在集合中只有一个文档,所以如果有不同的方法,那也很好。

以下是我的代码的外观:

(server.js的一部分)

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

setInterval(function(){

    request('http://www.reddit.com/r/gifs', 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);

1 个答案:

答案 0 :(得分:1)

您还需要清除urls数组。如果没有,它将继续增长。

您的代码可能正常运行,但是当您致电Gifs.create时,您正在传递urls,当您向其推送新的url时,该间隔每隔1分钟就会增长一次。

只需这样做就可以事先清除它:

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