Problems with using mongoose in Koa

Source: Internet
Author: User
Tags findone

Reprinted Please note:Theviper http://www.cnblogs.com/TheViper

Let's take a look at the following example.

This. login = function *(){
....... VaR q = usermodel. findone ({Email: name, PWD: Pwd}); q. select ('_ id'); q.exe C (function (ERR, ID) {If (ERR) return handleerror (ERR); this. body = ID ;});}

This is an Ajax login, but the response will return not found.

The crux of the problem is that no response is returned. Why is no response returned?

This is also quite easy to understand. Because the retrieval in q.execute is not implemented by this.body.specifically, mongoose's query q.exe C is an asynchronous operation, while the other side of KOA runs directly in the generator middleware mode regardless of whether the asynchronous operation is complete.

The solution is simple, that is, to convert the mongoose query to the generator middleware of KOA and add it to Koa, so Koa will not ignore the existence of the mongoose query.

You can rewrite q.exe C to the thunk format.

Function execquery (query) {return function (FN) {query.exe C (function (ERR, Res) {If (ERR) return FN (ERR); FN (null, res );});}}
Q = usermodel. findone ({Email: name, PWD: Pwd}); q. Select ('_ id'); this. Body = yield execquery (Q );

 

Problems with using mongoose in Koa

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.