2016-04-11 7 views
0

とundefinedを返します。私のexportsファイルで私の結果 は記録されませんが、私は私のProjects.findコール外の単純な文字列を返す場合、それは動作します。module.exportsは、私はマングースと私の<code>find</code>コールに<code>undefined</code>リターンを得続けるマングースコール

私はreq & resを渡しています。これらのファイルは、エクスポートファイルに正しく記録されているため、問題とは関係ありません。何が間違っているのでしょうか?それがためです

routes.js

var proj = require('./exports/projects'); 

app.use(function(req, res, next){ 
    //repsonse: undefined 
    console.log('response: ' + proj.test(req, res)); 
    next(); 
}); 

輸出/ projects.js

var Projects = require('../models/projects'); 

module.exports = { 
    test: function(req, res) { 
     Projects.find({'owner':req.user.id}, function(err, result) { 
       if (err) return '1'; 
       if (!result) 
        return null; 
       else 
        return result; 
     }); 
    } 
}; 

モデル/ projects.js

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var shortid = require('shortid'); 

var Projects = new Schema({ 
     projectid: String, 
     pname: { type: String, required: true, trim: true }, 
     owner: { type: String, required: true, trim: true }, 
     status: { type: String, default: '0' }, 
     team: String, 
     archived: { type: Boolean, default: '0' }, 
     created_at: Date 
}); 

Projects.pre('save', function(next) { 
    var currentDate = new Date(); 
    this.created_at = currentDate; 
    this.projectid = shortid.generate(); 
    next(); 
}); 

module.exports = mongoose.model('Projects', Projects); 

答えて

2

非同期の性質を有する。あなたは非同期関数で値を返そうとしていますが、これはしばらくしてから完了します。 console.log('response: ' + proj.test(req, res));proj.test(req, res)を実行しつつされる戻りに未定義の値を取得します。

ソリューションfind操作が完了すると実行されますコールバック関数を、渡す必要があります。

routes.js

app.use(function(req, res, next){ 

    proj.test(req,res,function(result){ 
     console.log('response',result); 
    }); 
    next(); 
}); 

輸出/ projects.js

module.exports = { 
    test: function(req, res, cb) { 
     Projects.find({'owner':req.user.id}, function(err, result) { 
       if (err) return cb(1); 
       if (!result) 
        return cb(null); 
       else 
        return cb(result); 
     }); 
    } 
}; 
+0

グレート答えのおかげで、私はそれはそれとは何かを知っていたが、私は、輸出と似たような状況がありましたそれがコールバックを必要としないように思えましたが、ページが代わりにレンダリングされたためである必要があります。総合的な答えにもう一度感謝します! – Aotik

関連する問題

 関連する問題