【问题标题】:How to return query results to a variable using mongoose如何使用猫鼬将查询结果返回给变量
【发布时间】:2014-01-09 02:22:18
【问题描述】:

我仍处于 Node.js 和 Moongoose 的学习阶段,我有一个场景在

  • 我正在从表单提交中获取值(ABC)。它是用户名
  • 然后我在用户集合(用户)中搜索该名称
  • 使用 ref 获取该用户并将其 ObjectID 写入另一个架构(文章)。

我的逻辑:

article.owner = User.findOne({ 'name' : 'ABC' })
    .exec(function (err, user){
         return user
    })

但它没有返回结果。我参考了其他一些答案并尝试了async.parallel,但我仍然无法在article.owner 的文章架构中保存ABC 用户的objectID,我总是得到null。

请建议我任何其他更好的方法。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    六氰化物的回答显示了如何通过另一个回调从异步数据库查找回调中携带数据。为我的项目救了我!

    Set Variable to result of Mongoose Find

    【讨论】:

      【解决方案2】:

      当 Node 必须进行任何 I/O 时,例如从数据库中读取,它将异步完成。像User.findOneQuery#exec 这样的方法永远不会预先返回结果,因此article.owner 在您的示例中不会正确地未定义。

      异步查询的结果仅在您的回调中可用,该回调仅在您的 I/O 完成时调用

      article.owner = User.findOne({ name : 'ABC' }) .exec(function (err, user){    
          // User result only available inside of this function!
          console.log(user) // => yields your user results
      })
      
      // User result not available out here!
      console.log(article.owner) // => actually set to return of .exec (undefined)
      

      在上面的例子中异步代码执行意味着什么:当 Node.js 命中 article.owner = User.findOne... 时,它将执行 User.findOne().exec(),然后在 .exec 完成之前直接移动到 console.log(article.owner)

      希望这有助于澄清。习惯异步编程需要一段时间,但多练习就会有意义

      更新要回答您的具体问题,一种可能的解决方案是:

      User.findOne({name: 'ABC'}).exec(function (error, user){
          article.owner = user._id; // Sets article.owner to user's _id
          article.save()            // Persists _id to DB, pass in another callback if necessary
      });
      

      如果您想像这样向用户加载文章,请记住使用Query#populate

      Article.findOne({_id: <some_id>}).populate("owner").exec(function(error, article) {
          console.log(article.owner); // Shows the user result
      });
      

      【讨论】:

      • 感谢 C Blanchard 的快速回答 :-) 但是这个答案并没有解决我的基本问题,即如何将用户名放入我需要在文章中分配此用户的 objectID 的其他集合(文章)中。所有者使用参考。如果您需要更多详细信息,请告诉我
      • damphat 之前的回答是对您的解决方案的回答,我只是想帮助您理解他的回答。无论如何我都会更新我的答案,因为有更多关于这个问题的信息
      【解决方案3】:
      User.findOne({ 'name' : 'ABC' }) .exec(function (err, user){
          article.owner = user.fieldName;
      })
      

      【讨论】:

      • 所以如果你添加了“console.log(article.owner);”在该函数之外,它会打印 user.fieldName?
      • 没有 michaelAdam,console.log 必须在里面,或者你可以使用 npm 'async' 等待回调
      猜你喜欢
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2022-01-06
      • 2019-09-29
      • 2018-08-22
      • 2017-05-08
      相关资源
      最近更新 更多