I
I
Igor Tkachenko2016-09-18 17:35:48
MongoDB
Igor Tkachenko, 2016-09-18 17:35:48

How to return data from model selected with findOne (mongoose)?

There is a controller that calls the model method to fetch data that needs to be returned back to the controller:
(model)

UsersSchema.methods.checkAuth = function(cookie) {	
  if(typeof cookie.crowder_main != 'undefined') {	 
    this.model('Users').findOne({hash: cookie.crowder_main}).exec(function (err, user){    
      if (err) return err;
      return user
    })	 
  } 	
}

But it’s clear that I won’t return data to the controller in this way, tell me how to do it better without crutches.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
catHD, 2016-09-19
@catHD

NodeJS -> DB -> callback/Promise

F
Faliah, 2016-09-21
@Faliah

Using Promise is very simple:

UsersSchema.methods.checkAuth = function(cookie) {	
  if(typeof cookie.crowder_main != 'undefined') {	
    var getUser = new Promise(function(resolve, reject) {
      this.model('Users')
      	    .findOne({hash: cookie.crowder_main})
            .exec(function (err, user){    
              if (err) reject(err);
              resolve(user)
    	    });
    })	
    getUser
    	.then(function(user) {
          // user получен - продолжаем работать с ним в контроллере
        })
        .catch(function(err) {
      	  // Обработка ошибки
        })
  } 	
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question