简体   繁体   中英

Module.exports returns undefined with Mongoose call

I keep getting an undefined return on my find call with Mongoose. My result in my exports file doesn't get logged, but it will work if I return a simple string outside my Projects.find call.

I'm passing req & res and they are logged correctly in my exports file, so don't think they have anything to do with the problem. Any ideas what's going wrong?

routes.js

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

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

exports/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;
        });
    }
};

models/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);

It is due to asynchronous nature of the Project.find() method. You are trying to return a value in asynchronous function, which gets completed after some time. Thus is gets undefined value in return while executing proj.test(req, res) in console.log('response: ' + proj.test(req, res)); .

Solution Need to pass a callback function, which gets executed once the find operation is done.

routes.js

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

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

exports/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);
        });
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM