这种奇怪的搜索模式(解构)在MongoDB承诺中是如何工作的?



在 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;

最新更新