gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:12:54 25 4
gpt4 key购买 nike

正在关注 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com