如何在猫鼬模型中使用 find 方法的回调结果

2024-04-04

我使用 mongoose 作为 Nodejs-mongodb 应用程序的 ODM。

这是我的第一个 Nodejs 应用程序,我来自非函数式编程背景。

看着docs http://mongoosejs.com/docs/index.html猫鼬你可以找到:

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

太棒了,这里我们将 find 函数作为模型(Kitten)的一部分,它实际上可以找到文档并在回调函数中将其检索为“kittens”,在本例中它使用 console.log() 。

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

I found 另一个问题 https://stackoverflow.com/questions/6854431/how-do-i-get-the-objectid-after-i-save-an-object-in-mongoose关于类似的询问 ObjectId 的问题,但当您使用回调仅使用 console.log 打印答案时,它们会提供相同类型的答案,如果我们诚实的话,这没有用。

由于我来自非函数式编程背景,我期待类似的内容:

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

据我所知,如果您在回调内分配一个新变量,则该变量的范围仅在回调函数内,与返回变量相同,即使在该方法之前声明一个变量也不起作用。

我确信我缺少一些东西。这个项目是如此之大,我认为他们不会忘记提供一种方法来做到这一点。我认为函数式编程中有些东西我遗漏了或者我不知道。

那么,如何才能实现这一目标呢?

Thanks !

编辑:我不知道为什么社区说我的问题可能是重复的如何从异步调用返回响应? https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call一般来说,这个问题更面向 js ajax async,这个问题面向 ODM 框架以及如何处理结果,它也可以通过 Promise 完成,并且是另一回事


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

那么如何解决您所面临的问题。我可以为你提供2种方式:

  • 使用回调
  • 使用承诺

回调

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

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
    }
});

请注意,由于这些异步操作的特定性,您必须在现有回调内继续执行所有其余操作。很快你就会面临“回调地狱”的问题。

有关回调和“回调地狱”的更多信息,您可以在那里阅读:

http://callbackhell.com/ http://callbackhell.com/

Promises

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

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
  });

因此,您只需在现有的承诺范围内工作,您可能会有越来越多的“然后”语句,例如:

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
  });

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在猫鼬模型中使用 find 方法的回调结果 的相关文章

随机推荐