在猫鼬模型中如何使用find方法的回调结果 [英] How to work with result of the callback of the find method in a mongoose model

查看:98
本文介绍了在猫鼬模型中如何使用find方法的回调结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将mongoose用作nodejs-mongodb应用程序的ODM.

I am using mongoose as ODM for a nodejs-mongodb application.

这是我的第一个nodejs应用程序,我来自非功能性编程背景.

Is my first nodejs application and I come from a non functional programming background.

查看猫鼬的文档,您可以找到:

Looking at the docs of mongoose you can find:

Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    console.log(kittens);
});

太好了,这里我们在模型中包含了find函数(小猫),它实际上可以找到文档并以小猫"的形式在回调函数中检索它,在这种情况下,它使用console.log()

So great, here we have the find function as part of our model (Kitten) and it actually can find the document and retrieve it inside the callback function as "kittens", and in this case it uses console.log() .

但是我想知道如何使用此函数式编程将此值分配给变量(因为我在models文件夹中的另一个文件中拥有此值,并且使用require导入了模块)

But I want to know how this functional programming is used to assign this value into a variable (because I have this in another file in the models folder and I import the module with require)

我找到了另一个问题,询问类似的对象要求,但当您使用回调仅使用console.log来打印答案时,它们提供相同的答案,如果说实话,这是没有用的.

I found another question about something similar asking for the ObjectId but they offer the same kind of answer when you use the callback to just use the console.log to print the answer and if we are honest this is not useful.

由于我来自非函数式编程背景,所以我期待这样的事情:

Since I come from a non functional programming background I was expecting something like:

var kitten = Kitten.find({name:'Silence'}); 

据我所知,如果您在回调内分配新变量,则该变量的作用域就在回调函数内,与返回变量相同,甚至在方法无法使用之前声明一个变量.

As far as I know if you assign a new variable inside the callback the scope of the variable is just within the callback function, the same with a return variable , even declaring a variable before the method is not gonna work.

我确定我缺少一些东西.这个项目是如此之大,我想他们不会忘记提供一种执行此操作的方法.我认为函数式编程中有某些内容我不知道或不知道.

Im sure there's something Im missing. This project is so big and I don't think they can't forget to offer a method to do this. I think there is something in the functional programming I am missing or I don't know.

那么,如何实现呢?

谢谢!

我不知道为什么社区会说我的问题是

I dont know why the community is saying that my question is a possible duplicate of How to return the response from an asynchronous call? this question is more oriented to js ajax async in general and this question is oriented to a ODM framework and how to handle the result that it can be done through promises too and is a different thing

推荐答案

我想告诉您,诸如访问数据库和检索数据之类的操作是异步操作,因此它们的工作方式有所不同,您不能只是像在基本同步操作中那样分配值.实际上,这就是Node.js的重点.如果您点击以下链接,则可以阅读更多内容: https://nodejs.org/about/

I would like to inform you that such kind of operations like accessing your database and retrieving data are async operations, so they are working differently and you can't just assign value like in basic sync operations. In fact that's the main point of Node.js. You may read more if you follow the link: https://nodejs.org/about/

因此,如何解决您遇到的问题.我可以为您提供2种方法:

So how to resolve the issue you have faced with. I can provide you with 2 ways:

  • 使用回调
  • 使用承诺

这实际上是您当前正在使用的内容.您需要运行基本函数并在其中放置另一个(回调)函数作为附加参数,因此一旦一切就绪,回调函数将被触发,您将能够获得结果.如何将结果接收到变量中:

That's actually what are you using at this moment. You need to run basic function and put there another (callback) function as additional argument, so once everything is ready callback function will be fired and you will be able to get results. How to receive results into your variable:

var searchQuery = {}; //or something specific like {name: 'Kitten Name'};
var foundKittens = [];
Kitten.find(searchQuery , function (err, kittens) {
    if (err) {
            //do something with error
    } else {
        foundKittens = kittens
    }
});

请注意,由于这些异步操作的特定性,您必须在现有回调中继续执行所有其余操作.很快,您将面临名为回调地狱"的问题.

Please note that all the rest actions you have to proceed inside of existing callback due to specific of these async actions. Soon you will faced with the issue called 'Callback Hell'.

有关回调和回调地狱"的更多信息,您可以在此处阅读:

More about callback and 'Callback Hell' you may read there:

http://callbackhell.com/

这是使用异步函数更容易理解和专业的方式.猫鼬ODM支持承诺( http://mongoosejs.com/docs/api.html#promise_Promise),因此您可以执行以下操作.

That's more understandable and professional way of working with asynchronous functions. Mongoose ODM supports promises (http://mongoosejs.com/docs/api.html#promise_Promise), so you may do the following.

var searchQuery = {}; //or something specific like {name: 'Kitten Name'};
var foundKittens = [];

Kitten
  .find(searchQuery)
  .exec()
  .then(function(kittens){
      //here you can assign result value to your variable
      //but this action is useless as you are working with results directly
      foundKittens = kittens;
      return kittens;
  })
  .onReject(function(err){
      throw err; //or something else
  });

因此,您只是在现有的Promise内工作,您可能会有越来越多的'then'语句,例如:

So then you just work inside of existing promise, you may have more and more 'then' statements like:

Kitten
  .find(searchQuery)
  .exec()
  .then(function(kittens){
      foundKittens = kittens;
      return kittens;
  })
  .then(countKittents)
  .then(changeSomethingInKittents)
  .then(saveKittentsToDb)
  .onReject(function(err){
      throw err; //or something else
  });

有关承诺的更多信息,请在此处阅读:

More about promises please read there:

http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

这篇关于在猫鼬模型中如何使用find方法的回调结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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