簡體   English   中英

MongoDB中這種奇怪的搜索模式(解構)如何工作?

[英]How does this weird search pattern (destructuring) work in MongoDB promises?

在mongo中關注這個問題后,我看到了引起我注意的事情(看看then()方法)

// connect to mongo, use Mongo Client
mongoose.connect(MONGO_URI, {useMongoClient: true})
  .then(({db: {databaseName}}) => console.log(`Connected to ${databaseName}`))
  .catch(err => console.error(err));

我確實理解在mongoose對象中有一個db屬性,下面有兩個或三個級別,這就是我想要的databaseName

我的問題

  • 它是ECMAScript2015還是一些黑暗的黑客?
  • 它有什么名字。 不知道如何在嘗試一段時間后找到它

謝謝

您正在看的是ES6破壞語法 ,而不是對象。

它的意思是:

  • 把參數傳遞給.then()
  • 在該對象上找到db屬性
  • 進一步構造db以查找其中的databaseName屬性
  • databaseName提升到當前范圍(在本例中為您的函數范圍)

最深層的變形變量將在當前范圍內可用。 這是一個例子:

 let { db: { databaseName } } = { db: { databaseName: 'ding' } } // now databaseName is available in the current scope console.log(databaseName) // prints "ding" 

這與用於執行ES6模塊導入的語法相同:

// import the entire module into the current scope
import something from 'something'
// import only parts of the module into the current scope
import { InsideSomething } from 'something'
// some people also destructure after importing and entire module
const { InsideSomething, another: { InsideAnother } } = something;

暫無
暫無

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

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