我正在使用meteor.js 和MongoDB 构建一个应用程序,我有一个关于cursor.forEach() 的问题。 我想在每次 forEach 迭代开始时检查一些条件,然后如果我不需要对其进行操作则跳过该元素,这样我可以节省一些时间。
这是我的代码:
// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection.forEach(function(element){
if (element.shouldBeProcessed == false){
// Here I would like to continue to the next element if this one
// doesn't have to be processed
}else{
// This part should be avoided if not neccessary
doSomeLengthyOperation();
}
});
我知道我可以使用 cursor.find().fetch() 将光标转换为数组,然后使用常规 for 循环遍历元素并正常使用 continue 和 break 但我很感兴趣是否有类似的东西可以使用在 forEach() 中。
最佳答案
forEach()
的每次迭代都会调用您提供的函数。要在任何给定的迭代中停止进一步处理(并继续下一项),您只需在适当的点从函数中 return
:
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});
https://stackoverflow.com/questions/18452920/
相关文章:
sql - MongoDB 在 v4 之前不符合 ACID 的真正含义是什么?
mongodb - Redis 比 mongoDB 快多少?
mongodb - 如何将 MongoDB 作为 Windows 服务运行?
mongodb - 如何在 MongoDB 中将集合从一个数据库复制到另一个数据库
mongodb - 如何重命名 MongoDB 中所有文档的字段?
mongodb - 如何在 mongo 控制台中通过 ObjectId 搜索对象?
java - 为什么 MongoDB Java 驱动程序在条件中使用随机数生成器?
mongodb - 如何在 Node.js 中使用 Mongoose 进行分页?