2017-10-28 56 views
0

有这个猫鼬没有找到最后创建的条目,直到我刷新页面

router.get('/documents', function(req, res, next) { 
    Document.find(function(err, doc){ 
    res.render('documents', { doc: doc }); 
    }); 
}); 

router.post('/documents', function(req, res, next) { 
    // Create function 
    req.body.newdocs.forEach(function(newdoc) { 
    Document.create({title : newdoc.title, desc: newdoc.desc}, function (err, ndoc) { 
     if (err) { 
     res.flash('error', "Error. Try again."); 
     res.redirect('/documents'); 
     } 
    }); 
    });  

    // Update function 
    req.body.docs.forEach(function(doc) { 
    var d = { 
     title: doc.title, 
     desc: doc.desc 
    } 
    Document.update({'_id': doc.id}, d, {overwrite: true}, function(err, raw) { 
     if (err) return handleError(err); 
    }); 
    }); 
    res.redirect('/documents'); 
}); 

当我创建一些文件,张贴(在数据库中创建的文档)和重定向工作。所以我得到的页面,但我只有有文件之前的帖子。当我刷新页面(再次获取页面)时,我有很好的新文档。

你有解释的一些想法,解决这个问题吗?

+0

您是否可以在不重新加载页面的情况下重新发送请求? – Nick

回答

0

你的代码中的问题是你不等待更新函数来完成。 :) 你告诉数据库保存文档用:

Document.update({'_id': doc.id}, d, {overwrite: true}... 

但蒙戈不更新异步,这意味着该代码将只对它们进行查询,并继续,无需等待实际更新。为了您的代码正确,您需要在回调中运行res.redirect('/documents');(这是在执行实际更新后执行后执行的功能)。 所以,你的代码应该是这样的:

Document.update({'_id': doc.id}, d, {overwrite: true}, function(err, raw) { 
    if (err) return handleError(err); 
    res.redirect('/documents'); 
}); 

Promise.all例如,通过要求@XavierB

//Push all of the promises into one array 
let promises = []; 
promises.push(Document.update({'_id': doc.id}, d, {overwrite: true})); 
//Await for all of the promises to be done 
Promises.all(promises).then(function(){ 
    //All of the promises were resolved 
    res.redirect('/documents'); 
}).catch(err => { 
    //Something went terribly wrong with ANY of the promises. 
    console.log(err); 
});; 
+0

原始代码在一对循环内执行多个数据库查询。使用'Promise.all'来等待它们可能会更好,而不是试着去调用回调。 – skirtle

+0

对,我的答案只是一个简化版本,重点解释为什么代码不起作用。 :)如果他想要替换两个循环,那么是的,Promise.all就是要走的路。 – vicbyte

+0

你能更精确吗?我怎样才能使用'Promise.all'?我发现这[回答](https://stackoverflow.com/questions/38362231/how-to-use-promise-in-foreach-loop-of-array-to-populate-an-object)但不知道究竟如何使用。 – XavierB

0

这是异步,它需要的时间才能完成。您应该使用async await或.then在回调中运行res.redirect('/'),它将按照您的预期工作

相关问题