簡體   English   中英

同步貓鼬和nodejs操作

[英]synchronise mongoose and nodejs operation

作為本次訓練營課程的一部分,我將學習與Mongoose,GraphQL和NodeJ一起構建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查詢中以及在運行查詢時,書籍和作者都鏈接在一起。

拋開整個故事的一部分。 當我的貓鼬中的操作結束時(因為貓鼬是異步的),我想退還書本(或者說我想退還books.save())。

我愚蠢地想到最后要做這樣的事情

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

但是,這里的歸還書是在返回承諾而不是在解決。

問題: MongoDB操作結束后如何返回解析? (或與MongoDB同步)

  1. 您需要將異步放在函數聲明上。
  2. 在模型上調用find時,請使用await,而不要在find()上傳遞函數回調

例如: const books = await book.find({name: args.name})將返回書本數組或null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM