Module.exports使用Mongoose调用返回undefined

时间:2016-04-11 22:20:53

标签: javascript node.js mongodb

我在undefined与Mongoose通话时不断获得find次回复。我的结果 在我的导出文件中没有记录,但如果我在Projects.find调用之外返回一个简单的字符串,它将起作用。

我正在通过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);

1 个答案:

答案 0 :(得分:2)

这是由于Project.find()方法的异步性质。您正在尝试在异步函数中返回一个值,该值将在一段时间后完成。因此,在proj.test(req, res)中执行console.log('response: ' + 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);
        });
    }
};