node.js - 如何使用 Mongoose 将查询结果返回给变量

标签 node.js mongodb mongoose

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

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

我的逻辑:

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

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

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

最佳答案

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

关于node.js - 如何使用 Mongoose 将查询结果返回给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20699947/

相关文章:

node.js - Nodejs Mongoose - 模型未定义

mongodb - 如何有效地聚合这些数据

jquery - 在 Node 中读取和编辑 HTML 文件的 DOM

node.js - express.js 有可变长度参数吗?

mongodb - 操作失败 : not authorized on tracking to execute command

javascript - Mongoose 和多数据库错误处理

node.js - PKCS7 在 Node.js 中加密解密

node.js - JavaScript 中的内存泄漏和关闭 - 何时以及为什么?

javascript - 使用 javascript 在 mongodb 终端中创建查询

javascript - 创建钩子(Hook)后