Module.exports通过Mongoose调用返回undefined

Module.exports returns undefined with Mongoose call

本文关键字:返回 undefined 调用 Mongoose exports 通过 Module      更新时间:2024-04-27

我在使用Mongoose的find调用中不断得到undefined返回。我的结果在我的导出文件中不会被记录,但如果我在Projects.find调用之外返回一个简单的字符串,它就会工作。

我正在通过req&res,并且它们正确地记录在我的导出文件中,所以不认为它们与问题有任何关系。你知道怎么了吗?

路由.js

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

导出/项目.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;
        });
    }
};

模型/项目.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);

这是由于Project.find()方法的异步性质。您正试图在异步函数中返回一个值,该函数将在一段时间后完成。因此,is在执行console.log('response: ' + proj.test(req, res));中的proj.test(req, res)时得到未定义的值作为返回。

解决方案需要传递一个回调函数,该函数将在find操作完成后执行。

路由.js

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

导出/项目.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);
        });
    }
};