Skip to content Skip to sidebar Skip to footer

How To Wait For The Return Of A Mongoose Search?

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 pr

Solution 1:

You don't really need to use Bluebird for this, as mongoose works just fine with native Promises

In your controller:

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

constCRUD = {
   retrieveOne: function(query) {
      // findOne() returns a Promise ()// https://mongoosejs.com/docs/promises.htmlreturnModel.findOne(query);
   }
}

module.exports = CRUD;

Now, you can make your route handler an async function and just await the Promise

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

router.post('/login', asyncfunction(req, res, next) { 
   let ret = await myCRUD.retrieveOne({ name: "abc test"}); 
   if(!ret) {
      res.redirect('/success')
   } else {
      res.redirect('/error')
   }
})

Solution 2:

Using async and await

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

router.post('/login', asyncfunction(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');
constSchema = require('./schema-user');
constModel = mongoose.model('users', Schema);

constCRUD = {
   retrieveOne: function(query) {
      returnnewPromise((resolve, reject) => {
        Model.findOne(query, function(err, result) {
           if (err) reject(err);
           resolve(result);
        });
      });
   }
}

module.exports = CRUD;

Post a Comment for "How To Wait For The Return Of A Mongoose Search?"