2013-07-24 150 views
5

寫作:如何終止一個MongoDb shell腳本?

if (...) { 
    return; 
} 
在MongoDB的shell腳本

會抱怨:SyntaxError: return not in function

我也曾嘗試exit蒙戈控制檯命令:

if (...) { 
    exit; 
} 

但你的錯誤:ReferenceError: exit is not defined

如何在之前終止執行腳本文件?

回答

12

在mongodb中,您可以使用quit()函數記錄here。雖然沒有很好的記錄,但我做了一個快速測試,可以通過執行quit(1)返回非零退出代碼,該代碼將退出帶狀態1.

+1

請注意是否要在Robomongo嘗試它。它將立即關閉整個應用程序。 [測試OSX,Robomongo 1.0.0-RC1] –

+0

發生在@ @ŁukaszMazan,我在閱讀您的評論後立即關閉 - –

2

後的話題某些搜索似乎首選的方式來阻止JavaScript執行與exit LIKE語句是實際扔東西:Is it possible to stop JavaScript execution?,這個問題要麼是最常見的例子還是在我看來,只有一個會合理工作。

2

我已經使用了以下解決方案:

(function(){ 

    // now you can use the return keyword anywhere: 
    if (/* some condition */) { 
     print("This is an error condition"); 
     return; 
    } 

})(); 

我知道終止腳本這樣不會讓mongo返回錯誤代碼不是0(作爲接受的解決方案一樣)。