簡體   English   中英

將其他參數傳遞給Mongoose查詢

[英]Passing additional parameter to Mongoose query

我想將其他參數傳遞給Mongoose findOne查詢。

這是我的偽代碼:

for (var i = 0; i < 5; i++) {
    SomeCollection.findOne({name: 'xxx' + i}, function (err, document) {
        if (document) {
            console.log('aaa' + i + document.somefield);  
        }
    });
}  

正如您所看到的,我在findOne回調中使用了i變量值,因為它在不同的線程中運行,我想將它傳遞給findOne方法。

我該怎么做?

只要您使用node.js 4.x或更高版本,就可以通過在for循環中使用let而不是var來有效地為每次迭代創建一個新范圍:

for (let i = 0; i < 5; i++) {
    SomeCollection.findOne({name: 'xxx' + i}, function (err, document) {
        if (document) {
            // i will have the same value from the time of the findOne call
            console.log('aaa' + i + document.somefield);  
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM