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

标签 javascript node.js mongodb ecmascript-6 promise

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

相关文章:

javascript - 带重复的背包 - 阵列解决方案

javascript - 尝试使用 'group ' 和 find() 在 Mongoose 中执行 '$expr' 时出错

mongodb - 如何知道MongoDB集合大小?

javascript - 包含来自 vuex 的 mapGetters

javascript - 如何使用 d3 绘制动画折线图,同时需要每 1 秒更新一次数据表?

javascript - 在 Windows 中,我们如何让 Electron js 应用程序在任务管理器中保持运行

node.js - 使用node.js 谷歌地图客户端库

javascript - Webpack 需要什么配置才能完成这些事情?

node.js - 如何在 Mongoose 查询中连接多个字段?

javascript - 在一个 ajax 帖子上发布表单和文本区域