NodeJS模块中的函数返回返回undefined,但它不是真的

时间:2015-03-23 22:36:30

标签: javascript node.js mongodb

我的NodeJS应用程序中有一个mongo.js模块,我尝试检查文档是否存在,如果没有,保存到数据库,如果是,则将错误返回到称为模块函数的routes.js文件。

这是我的模块:

var appRoot = require('app-root-path'),
config = require(appRoot + '/config/config'),
db = require('mongojs').connect(config.db.host);

module.exports = {
    saveSpammer: function(ip, userAgent, fn) {
        var exist = this.find('spammers', {ip:ip, userAgent:userAgent});

        console.log(exist); // returns undefined

        if (!exist) {
            return this.save('spammers', {ip: ip, userAgent: userAgent, date: (new Date())}, fn);
        } else {
            return fn('You have already submitted a request!');
        }
    },

    save: function(col, data, fn) {
        var col = this.getCol(col);

        col.insert(data, {w:1}, function(err, records) {
            if (err) {
                return fn(err);
            } else {
                return fn(null, records);
            }
        });
    },

    find: function(col, query, fn) {
        var col = this.getCol(col);

        col.find(query, function(err, docs) {
            console.log(docs); // returns list of documents from mongo
            console.log(docs ? 1 : 0); // returns 1

            if (docs) {
                return true;
            } else {
                return false;
            }
        });
    }
}

当我在查找函数中输出“docs”变量时,我看到正确的数据,然后基于它我根据文档的存在返回true或false,问题是从函数find返回函数saveSpammer给了我“不确定”。

我在JavaScript中使用常规函数返回,也许我在NodeJS的概念中遗漏了一些东西?

请协助

1 个答案:

答案 0 :(得分:3)

您的示例中的问题是col.find()调用是异步执行的。

所以

var exist = this.find('spammers', {ip:ip, userAgent:userAgent});
console.log(exist); // returns undefined

是预期的行为,因为this.find不会返回任何内容。您可以看到return函数的定义中没有find

您需要使用回调机制

this.find('spammers', {ip:ip, userAgent:userAgent}, function(err, exist) {
    console.log(exist);
    .. rest of the code here
});

并使用

修改find功能
if (err) {
    fn(err);
} else if (docs) {
    fn(null, true);
} else {
    fn(null, false);
}