是什么?

.exec().save() 一样是 Mongoose 的异步操作,都返回一个 thenable

怎么用?

我们先定义一个 query 对象: const query = MyModel.findOne({}),接下来我们一般会这么使用:

query.then(doc => {...})
// or
const doc = await query.exec()

有什么区别?

  • query 本身并不是 Promise 对象,它只是实现了 .then.catch 方法便于异步操作;

  • .exec() 返回了一个真正的 Promise 对象。

但 query 提供了 .then 方法,我们一样可以使用 async/await :

const doc = await query
// or
const doc = await query.exec()

以上两种写法已近乎一致,而事实上它们在功能执行上也 完全一致

是否需要使用 .exec()

官方建议使用 .exec() ,因为它在使用 async/await 时提供了更好的堆栈跟踪。

以官方示例:

const doc = await Band.findOne({ name: "Guns N' Roses" }); // works

const badId = 'this is not a valid id';
try {
await Band.findOne({ _id: badId });
} catch (err) {
// Without `exec()`, the stack trace does **not** include the
// calling code. Below is the stack trace:
//
// CastError: Cast to ObjectId failed for value "this is not a valid id" at path "_id" for model "band-promises"
// at new CastError (/app/node_modules/mongoose/lib/error/cast.js:29:11)
// at model.Query.exec (/app/node_modules/mongoose/lib/query.js:4331:21)
// at model.Query.Query.then (/app/node_modules/mongoose/lib/query.js:4423:15)
// at process._tickCallback (internal/process/next_tick.js:68:7)
err.stack;
} try {
await Band.findOne({ _id: badId }).exec();
} catch (err) {
// With `exec()`, the stack trace includes where in your code you
// called `exec()`. Below is the stack trace:
//
// CastError: Cast to ObjectId failed for value "this is not a valid id" at path "_id" for model "band-promises"
// at new CastError (/app/node_modules/mongoose/lib/error/cast.js:29:11)
// at model.Query.exec (/app/node_modules/mongoose/lib/query.js:4331:21)
// at Context.<anonymous> (/app/test/index.test.js:138:42) <--- here
// at process._tickCallback (internal/process/next_tick.js:68:7)
err.stack;
}

可以看到,使用 .exec() 时能直接追踪到异常位置: index.test.js:138:42

参考:

https://mongoosejs.com/docs/promises.html

mongoose中的exec()有什么用?的更多相关文章

  1. Mongoose中关联查询populate的使用

    MongoDB中没有join的特性,因此无法使用join进行表的连接和关联查询,在Mongoose中封装了populate方法,在定义一个 Schema 的时候可以指定了其中的字段(属性)是另一个Sc ...

  2. 正则表达式中的exec和match方法的区别

    正则表达式中的exec和match方法的区别 字符串的正则方法有:match().replace().search().split() 正则对象的方法有:exec().test() 1.match m ...

  3. python中eval, exec, execfile,和compile [转载]

    eval(str [,globals [,locals ]])函数将字符串str当成有效Python表达式来求值,并返回计算结果. 同样地, exec语句将字符串str当成有效Python代码来执行. ...

  4. [原译]在mongoose中对Array Schema进行增删改

    原文地址: http://tech-blog.maddyzone.com/node/add-update-delete-object-array-schema-mongoosemongodb 本文为上 ...

  5. js正则表达式中test,exec,match方法的区别说明

    js正则表达式中test,exec,match方法的区别说明 test test 返回 Boolean,查找对应的字符串中是否存在模式.var str = "1a1b1c";var ...

  6. mongoose中connect()、createConnection()和connection的区别和作用

    转文:原文 1 mongoose简介 在使用mongodb数据库开发项目中,nodejs环境下可能会使用到mongoose模块连接并操作mongodb数据库.mongoose模块相当于Java中的数据 ...

  7. Python中的exec、eval使用实例

    Python中的exec.eval使用实例 这篇文章主要介绍了Python中的exec.eval使用实例,本文以简洁的方式总结了Python中的exec.eval作用,并给出实例,需要的朋友可以参考下 ...

  8. find中的-exec参数

    1.find中的-exec参数 在当前目录下(包含子目录),查找所有txt文件并找出含有字符串"bin"的行 find ./ -name "*.txt" -ex ...

  9. mongoose中的流查询stream query

    mongoose中的流查询stream query,功能类似于php中的mysql_fetch_array,每次从集合中获取一条记录(文档) var cursor = Person.find({ oc ...

  10. mongoose中给字段添加索引的方法

    mongoose中给字段添加索引的方法有两种,一种通过在定义schema的时候配置,如: var animalSchema = new Schema({ name: String, type: Str ...

随机推荐

  1. RxJS 系列 – Error Handling Operators

    前言 前几篇介绍过了 Creation Operators Filter Operators Join Creation Operators 这篇继续介绍 Error Handling Operato ...

  2. Python 潮流周刊#69:是时候停止使用 Python 3.8了(摘要)

    本周刊由 Python猫 出品,精心筛选国内外的 250+ 信息源,为你挑选最值得分享的文章.教程.开源项目.软件工具.播客和视频.热门话题等内容.愿景:帮助所有读者精进 Python 技术,并增长职 ...

  3. 月薪20k以上的软件测试工程师的必备知识点?全部拿走吧!

    我们都知道作为一个软件测试工程师,入门相对比较简单,但是要达到技术精通,甚至薪资能达到20k以上的话,那绝对需要对测试开发有一个系统的了解,以及对这些系统的知识能够熟练掌握. 今天的话是我从阿里以为做 ...

  4. SpringMVC——SSM整合——表现层数据封装

    表现层数据封装 设置统一数据返回结果类 注意:Result类中的字段并不是固定的,可以根据需要自行增减提供若干个构造方法,方便操作 返回结果类 package com.cqupt.controller ...

  5. 数据库周刊59丨GaussDB(for openGauss)开放商用;人大金仓保障冬奥会演练顺利完成;MDL锁导致的MySQL问题分析;PG日志使用手册;达梦表空间查询;数据库笔试题面试题集……

    热门资讯 1.openGauss 上线华为云正式商用 - GaussDB(for openGauss) [摘要]近日,GaussDB(for openGauss)已于华为云官网全面开放商用.该产品是华 ...

  6. C#的函数使用 和参数修饰符 out ref params

    // 函数和方法 // 函数好比对象的动作行为 在定义函数的时候,职责(作用/功能)越单一越好 满足高内聚 低耦合的开发思路 // 变量的命名规则 小驼峰 // 函数的命名规则 大驼峰 动词开头 // ...

  7. px 、em、rem 的选取依据

    1. px 像素(Pixel).绝对单位.像素px是相对于显示器屏幕分辨率而言的,是一个虚拟长度单位,是计算机系统的数字化图像长度单位,如果 px要换算成物理长度,需要 指定精度 DPI. 2. em ...

  8. 创建一个简单的基于MyBatis的项目

  9. 初学者浅析C++类与对象

    C++类与对象 class class基本语法 class ClassName { public: // 公有成员 Type memberVariable; // 数据成员 ReturnType me ...

  10. 正态分布——“牛而B之”

    1 问题: 什么是正态分布,为什么这么出名和重要? 1.1 名气大 为什么叫"正态分布",也有地方叫"常态分布",这两个名字都不太直观,但如果我们各取一字变为& ...