是什么?

.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. 实战合集 | I/O 2021 Flutter 研讨会

    2021 年的 Google I/O 大会已圆满闭幕,本次大会带来了诸多关于各项谷歌开发技术产品的最新更新.在此次 I/O,Flutter 发布了 2.2 版本,包括 Web 版的增强.更多 Mate ...

  2. Kubernetes ReplicaSet 控制器(十九)

    前面我们一起学习了 Pod 的原理和一些基本使用,但是在实际使用的时候并不会直接使用 Pod,而是会使用各种控制器来满足我们的需求,Kubernetes 中运行了一系列控制器来确保集群的当前状态与期望 ...

  3. 多Master节点的k8s集群部署-完整版

    多Master节点的k8s集群部署 一.准备工作 1.准备五台主机(三台Master节点,一台Node节点,一台普通用户)如下: 角色 IP 内存 核心 磁盘 Master01 192.168.116 ...

  4. JNI和HAL 的区别

    JNI (Java Native Interface) 和 HAL (Hardware Abstraction Layer) 在 Android 系统中都扮演着与本地代码交互的重要角色,但它们的功能和 ...

  5. vue3中的vue-18n的table表格标题不动态变化中英文

    使用 computed 即可 eg: const columns = computed(() => { return reactive<any>([ { title: proxy.$ ...

  6. NVM使用说明

    下载:https://github.com/coreybutler/nvm-windows/releases 切换镜像源:  settting.txt文件后面添加 node_mirror: https ...

  7. ProxyPin 抓包,原来可以这么简单!

    ​ 你是否还在为网络请求的抓包发愁?其实,ProxyPin 可以让抓包操作变得异常简单!不需要复杂的设置,也不用繁琐的配置,轻松几步就能实现.让我们一起来看看吧! 抓包操作常用于测试网络请求.分析接口 ...

  8. 为重复使用的HttpClient对象动态修改Timeout

    最近博客园被**了, 赶紧水一文支持一下博客园,加油! 问题现象 当HttpClient被使用过之后, 在修改它们的属性会抛出错误This instance has already started o ...

  9. Win11使用Translucent TB设置Windows导航栏透明失败解决方案

    Win11使用Translucent TB设置Windows导航栏透明失败解决方案 Translucent TB下载方式:直接在Windows自带的Microsoft应用商店里面搜索下载就可以了 1. ...

  10. KubeSphere 社区双周报 | 本周六上海站 Meetup 准时开启 | 2023.7.21-08.03

    KubeSphere 社区双周报主要整理展示新增的贡献者名单和证书.新增的讲师证书以及两周内提交过 commit 的贡献者,并对近期重要的 PR 进行解析,同时还包含了线上/线下活动和布道推广等一系列 ...