[英]synchronise mongoose and nodejs operation
As a part of bootcamp course I am going through, I am learning building restful API's along with Mongoose, GraphQL and NodeJs. 作为本次训练营课程的一部分,我将学习与Mongoose,GraphQL和NodeJ一起构建Restful API。
Here is my code 这是我的代码
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
}
Now, While this works, the problem is that books and author are linked together in GraphQL query and when running the query. 现在,尽管可行,但问题是在GraphQL查询中以及在运行查询时,书籍和作者都链接在一起。
Putting aside the entire story part. 抛开整个故事的一部分。 I want to return books (or let's say I want to do return books.save()) when the operation in my mongoose is over (since mongoose is async)
当我的猫鼬中的操作结束时(因为猫鼬是异步的),我想退还书本(或者说我想退还books.save())。
I stupidly thought about doing something like this in the end 我愚蠢地想到最后要做这样的事情
books.save()
}).then(() => {
return books
})
}
but then return books here is returning the promise and not the resolve. 但是,这里的归还书是在返回承诺而不是在解决。
Question: How can I return resolve after my MongoDB operation is over? 问题: MongoDB操作结束后如何返回解析? (or in sync with MongoDB)
(或与MongoDB同步)
Ex: const books = await book.find({name: args.name})
which will return array of books or null 例如:
const books = await book.find({name: args.name})
将返回书本数组或null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.