正在关注 this 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 还是一些黑暗的 hack?
- 它有什么名字。尝试了一段时间后不知道如何找到它
谢谢
最佳答案
您正在查看的是 ES6 destructing syntax ,不是对象。
它的意思是:
- 将参数传递给
.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;
关于javascript - 这种奇怪的搜索模式(解构)在 MongoDB promises 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892010/