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