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

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

问题描述

我遇到了一段Mongoose代码,其中包含一个查询findOne,然后是一个exec()函数。

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

我以前从未在Javascript中看过那个方法?它究竟做了什么?

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

推荐答案

基本上使用mongoose时,可以使用帮助程序检索文档。接受查询条件的每个模型方法都可以通过回调 exec 方法执行。

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.

回调

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.

您可以在 mongoose docs

更新

需要注意的事项使用 Promises 与Mongoose异步操作相结合的是Mongoose查询承诺。查询会返回 thenable ,但如果您需要真实的承诺,则应使用 exec 方法。有关详细信息,请访问此处

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:


我以前从未在Javascript中看到过这种方法?它究竟做了什么

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

那么它是不是原生JavaScript方法,而是Mongoose API。

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

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

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