maria maria - 3 months ago 15
Node.js Question

return resolve error in node function

Why wont usernametoid function return the acual id? cause im trying to send the result of the userdata as the return. In this case, i want to only send the userdata`s _id attribute. but it seems like it wont work.

console.log(userdata._id); // works
return resolve(userdata._id); // wont work.


output of variable userdata:

{
cash: 7300002,
bank: 0,
xp: 0,
rank: 1,
points: 1,
location: 1,
health: 100,
protection: 1,
attack: 1,
family: '0',
password: 'jKa4qC7pRCgE5jvzD9Vv1pRUNxFlQEM7Jpq/IoJ/sUWOAv1Wx1RI/j/Vu6Zf8zyNkCFcg3QBtdfAC+lmPS8KIA==',
profileImageURL: 'modules/users/client/img/profile/default.png',
roles: [ 'user' ],
created: Sat Aug 27 2016 12:33:55 GMT-0400 (EDT),
__v: 0,
username: 'signature',
provider: 'local',
salt: '4ySlrr9ggESxBB3dR5bx4Q==',
_id: 57c1c0f3b6b20c011242bf22 }


when i do: `return resolve(userdata._id) it would get this error:

/server/factory/user_factory.js:52
return resolve(userdata._id);
^

TypeError: Cannot read property '_id' of null


node.js call:

var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));


var userFunc = require('../factory/user_factory.js');
app.post('/api/kill', function (req, res) {

console.log("starting");
var username = "signature";//req.query.username;

var result = ["test service"];

var data = req.user;
userFunc.usernametoid(username).then( function (otherplayerid) {


if (!(otherplayerid)) {
console.log("other player is acually " + otherplayerid);
result.push("denne brukeren finnes ikke! " + otherplayerid);

} else {

userFunc.usernametoid(otherplayerid).then( function (otherplayer) {
if (data.location != otherplayer.location) {
result.push("Du er ikke i samme lokasjon som " + username);
result.push(data.location + " vs " + otherplayer.location);
} else {

userFunc.addCash(req.user._id,100000);
result.push("starter lokasjonisering");

}
});
}
res.json(result);
});

});


user factory:

var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));




exports.usernametoid = usernametoid;

function usernametoid(id) {

return new Promise( function (resolve, reject) {
var query = Users.findOne( { username : id } );

// var query = Users.find({_id:id});
query.exec(function(err, userdata) {
if (err){
return reject({err : 'Error while getting user info'});
}


console.log(userdata._id);
return resolve(userdata);
});

}, function (){
return reject({err : 'error while fetching cash'});
});
}

Answer

Because you are not passing correctly the fetched user to the query.exec.

You need to do:

var Users  = require('../models/users-model.js');

function usernametoid(id) {
    return new Promise( function (resolve, reject) {
        Users.findOne({ username : id }).then( function(user){
          //If you use lodash you can do _.isNull(user)
          if(user == null){
            return reject({error : 'User not found'});
          }

          user.exec(function(userdata, error) {
              if(userdata){
                return resolve(userdata);
              } 
              if(error){
                 return reject({error : 'Error while executing query'});
              }
           });
        });
    });
}

I don't really get why you are importing Users Model like that. I do not think Node will be able to fetch it like that.

And, you should require mongoose in your server.js

To catch the rejection you need the following code:

UserFactory.userNameToId(id).then( function(response){
  if(response.error){
    console.log('error '+response.error);
  }
  if(response){
    console.log('Got response '+response);
  }
});