mongoose.js Model.remove 在一个循环中只工作一次
mongoose.js Model.remove only works once within a loop
我不确定这只是我对异步编程的新手还是一个实际的错误,但每当我将 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);
您还需要清除 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);
});
}
我不确定这只是我对异步编程的新手还是一个实际的错误,但每当我将 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);
您还需要清除 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);
});
}