【问题标题】:synchronise mongoose and nodejs operation同步 mongoose 和 nodejs 操作
【发布时间】:2019-03-25 10:33:59
【问题描述】:

作为我正在学习的训练营课程的一部分,我正在学习与 Mongoose、GraphQL 和 NodeJs 一起构建 restful API。

这是我的代码

resolve (parent, args) {

                let books = new book({
                    name: args.name, 
                    genre: args.genre,
                    authorName: args.authorName
                })    

                let author = new Author({ 
                    name: args.authorName
                })

                book.find( 
                    {
                        name: args.name
                    }, function(error, results) {
                        if (results.length == 0 ) {
                            Author.find(
                                {
                                  name: args.authorName
                                },
                                function (err, result) {
                                    if (result.length == 0) {    
                                    author.save()
                                  }
                                 })
                              }
                              books.save()  
                            })
                    return books
            }

现在,虽然这可行,但问题是书籍和作者在 GraphQL 查询中和运行查询时链接在一起。

抛开整个故事部分。当我的 mongoose 中的操作结束时(因为 mongoose 是异步的),我想归还书籍(或者假设我想要返回 books.save())

我愚蠢地想到最后做这样的事情

             books.save()  
                            }).then(() => {
                    return books
                })
            }

但是这里还书是返回承诺而不是解决。

问题: MongoDB 操作结束后如何返回 resolve? (或与 MongoDB 同步)

【问题讨论】:

  • 尝试使用异步/等待

标签: javascript node.js mongoose


【解决方案1】:
  1. 您需要将异步放在函数声明中。
  2. 在模型上调用 find 时,使用 await 而不是在 find() 上传递函数回调

例如:const books = await book.find({name: args.name}) 这将返回书籍数组或 null

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 2022-09-23
    • 2021-04-08
    • 2014-08-23
    • 2019-05-27
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多