如何等待猫鼬搜索的返回? [英] How to wait for the return of a Mongoose search?

查看:50
本文介绍了如何等待猫鼬搜索的返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用NodeJS/Mongoose创建了一个CRUD,将文件拆分为MVC样式.在下面显示的路由示例中,当执行 retrieveOne 例程时,有必要等待其处理,然后将用户重定向到一条路由或另一条路由.我想使用Bluebird等待处理.我需要一些帮助来实现例程.

I created a CRUD with NodeJS / Mongoose, split the files in MVC style. In route example I show up below, when the retrieveOne routine is executed, it's necessary to wait for its processing and then redirect the user to one route or another. I'd like to use Bluebird to wait for processing. I need some help to implement the routine.

Index.js -----------------------------------------------

Index.js -----------------------------------------------

const myCRUD = require('./api/controllers/controller')

router.post('/login', function(req, res, next) {   

   // HOW TO IMPLEMENT BLUEBIRD HERE?

   // How to wait for the "retrieveOne" process and a then do a "if" test (below)?   
   let ret = myCRUD.retrieveOne({ name: "abc test" }); 


   if(!ret) {
      res.redirect('/success')
   } else {
      res.redirect('/error')
   }
})

controller.js ------------------------------------------

controller.js ------------------------------------------

const mongoose = require('mongoose');
const Schema = require('./schema-user');
const Model = mongoose.model('users', Schema);

const CRUD = {
   retrieveOne: function(query) {
      Model.findOne(query, function(err, result) {
         if (err) return err;
         return result;
      });
   }
}

module.exports = CRUD;

注意:我已经在S.O.中找到了一些带有和不带有Bluebird的示例,但是我无法使它正常工作:示例: 1 3 5

Note: I've already found several examples with and without Bluebird right here in S.O., but I couldn't get it to work: Examples: 1, 2, 3, 4, 5

推荐答案

使用 async await

const myCRUD = require('./api/controllers/controller')
const Promise = require('bluebird');

router.post('/login', async function(req, res, next) {   

   // HOW TO IMPLEMENT BLUEBIRD HERE?

   // How to wait for the "retrieveOne" process and a then do a "if" test (below)?   
   let ret = await myCRUD.retrieveOne('{ name: "abc test"'); 


   if(!ret) {
      res.redirect('/success')
   } else {
      res.redirect('/error')
   }
})

// controller.js ------------------------------------------

const mongoose = require('mongoose');
const Schema = require('./schema-user');
const Model = mongoose.model('users', Schema);

const CRUD = {
   retrieveOne: function(query) {
      return new Promise((resolve, reject) => {
        Model.findOne(query, function(err, result) {
           if (err) reject(err);
           resolve(result);
        });
      });
   }
}

module.exports = CRUD;

这篇关于如何等待猫鼬搜索的返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆