我还在学习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必须执行任何I / O操作时,例如从数据库读取,它将以异步方式完成. User.findOne和Query #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()然后直接进入console.log(article.owner)在.exec甚至完成之前.
希望有助于澄清.它需要一段时间才能习惯异步编程,但是通过更多练习它会有意义
更新要回答您的具体问题,一种可能的解决方案是:
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 });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。