Mongoose - exec 函数有什么作用? [英] Mongoose - What does the exec function do?

查看:32
本文介绍了Mongoose - exec 函数有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一段 Mongoose 代码,其中包含一个查询 findOne 和一个 exec() 函数.

我以前从未在 Javascript 中见过这种方法吗?它究竟是做什么的?

解决方案

基本上在使用 mongoose 时,可以使用 helper 来检索文档.每个接受查询条件的模型方法都可以通过 callbackexec 方法执行.

回调:

User.findOne({ name: 'daniel' }, function (err, user) {//});

exec:

用户.findOne({ 名称: '丹尼尔' }).exec(函数(错误,用户){//});

因此,当您不传递回调时,您可以构建查询并最终执行它.

您可以在 mongoose 文档中找到更多信息.>

更新

组合使用 Promises 时的注意事项Mongoose 异步操作的特点是 Mongoose 查询不是 Promises.查询确实返回一个 thenable,但是如果你需要一个 real Promise,你应该使用 exec 方法.可以在此处找到更多信息.

在更新期间,我注意到我没有明确回答问题:

<块引用>

我以前从未在 Javascript 中见过这种方法吗?它有什么作用是吗?

好吧,它不是原生 JavaScript 方法,而是 Mongoose API 的一部分.

I came across a piece of Mongoose code that included a query findOne and then an exec() function.

Ive never seen that method in Javascript before? What does it do exactly?

解决方案

Basically when using mongoose, documents can be retrieved using helpers. Every model method that accepts query conditions can be executed by means of a callback or the exec method.

callback:

User.findOne({ name: 'daniel' }, function (err, user) {
  //
});

exec:

User
  .findOne({ name: 'daniel' })
  .exec(function (err, user) {
      //
  });

Therefore when you don't pass a callback you can build a query and eventually execute it.

You can find additional info in the mongoose docs.

UPDATE

Something to note when using Promises in combination with Mongoose async operations is that Mongoose queries are not Promises. Queries do return a thenable, but if you need a real Promise you should use the exec method. More information can be found here.

During the update I noticed I didn't explicitly answer the question:

Ive never seen that method in Javascript before? What does it do exactly?

Well it's not a native JavaScript method, but part of the Mongoose API.

这篇关于Mongoose - exec 函数有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆