Module.exports通过Mongoose调用返回undefined
Module.exports returns undefined with Mongoose call
我在使用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);
});
}
};
相关文章:
- RequireJS向模块传递配置总是返回undefined
- JSON数组数据返回Undefined
- JavaScript”;.方法“;返回undefined
- jQuery可以't获取data-*属性值,返回undefined
- Javascript/JSON警报返回Undefined
- Javascript:firstChild对象返回undefined
- 当尝试使用ajax读取文件时,变量返回undefined
- 如何避免JSON.stringify在特殊情况下返回undefined,从而为JSON.parse创建字符串失败
- 使用谷歌地图:一个返回undefined的自定义javascript函数
- Json在nodeJs和AngularJs中返回undefined
- 为什么像 Firefox 和 Chrome 控制台中的 '}{' 这样的结构会返回 'undefined'?
- 使用 HTML 和 JavaScript 从表单访问值时返回 undefined
- 在 CoffeeScript 中,当尝试调用类中的方法 (@_methodName) 时,它会返回 undefined
- 解析承诺'当'返回undefined(Javascript)
- NodeJS:zlib.gunzip(body)错误地返回“undefined”
- window.open在chrome扩展中返回undefined
- jQuery.pr()返回undefined,而.attr()对数据-*的作用与预期一样
- 正在读取嵌套json,jquery返回undefined
- IIFE是否总是返回undefined
- $timeout包装$http.post返回undefined而不是promise