【问题标题】:Node.js | TypeError: [...] is not a functionNode.js | TypeError: [...] 不是函数
【发布时间】:2018-03-19 02:20:10
【问题描述】:

在我的主文件 server.js 中,我有以下功能:

server.js

const mongoose = require('mongoose');
const SmallRounds = require('./models/smallrounds.js');

function initRound(){
    logger.info('Initializing round...');
    SmallRounds.getLatestRound((err, data) => {
        [...]
    });
}

函数 getLatestRound() 被导出到我的猫鼬模型 smallrounds.js 中

smallrounds.js

const mongoose = require('mongoose');
const config = require('../config.js');

const SmallRoundsSchema = mongoose.Schema({
    [...]
});

const SmallRounds = module.exports = mongoose.model('SmallRounds', SmallRoundsSchema);

module.exports.getLatestRound = function(callback){
    SmallRounds.findOne().sort({ created_at: -1 }).exec((err, data) => {
        if(err) {
            callback(new Error('Error querying SmallRounds'));
            return;
        }
        callback(null, data)
    });
}

但是当我调用 initRound() 时出现以下错误:

TypeError: SmallRounds.getLatestRound 不是函数

在 initRound (E:\Projects\CSGOOrb\server.js:393:14)
在 Server.server.listen (E:\Projects\CSGOOrb\server.js:372:2)
在 Object.onceWrapper (events.js:314:30)
在 emitNone (events.js:110:20)
在 Server.emit (events.js:207:7)
在 emitListeningNT (net.js:1346:10)
在 _combinedTickCallback (internal/process/next_tick.js:135:11)
在 process._tickCallback (internal/process/next_tick.js:180:9)
在 Function.Module.runMain (module.js:607:11)
启动时 (bootstrap_node.js:158:16)
在 bootstrap_node.js:575:3

为什么会这样?我不认为我有循环依赖,也没有拼错任何东西。谢谢:)

【问题讨论】:

  • 可能mongoose.model 中返回的对象被冻结了还是什么?确保您需要的文件与本文中的完全一致。
  • 是的,我复制粘贴了代码

标签: javascript node.js mongoose


【解决方案1】:

我使用大写模块,并收到错误TypeError: upperCase is not a function l

et upperCase =require("upper-case") ;
res.end(upperCase("Hello World"));

每个教程都是这样写的。

我改成

res.end(upperCase.upperCase("Hello World"));

工作正常

【讨论】:

    【解决方案2】:

    这不是您向 Mongoose 模型/模式添加方法的方式。

    试试这个:

    const mongoose = require('mongoose');
    const config = require('../config.js');
    
    const SmallRoundsSchema = mongoose.Schema({
        [...]
    });
    
    SmallRoundsSchema.statics.getLatestRound = function(callback){
        this.findOne().sort({ created_at: -1 }).exec((err, data) => {
            if(err) {
                callback(new Error('Error querying SmallRounds'));
                return;
            }
            callback(null, data)
        });
    }
    
    const SmallRounds = module.exports = mongoose.model('SmallRounds', SmallRoundsSchema);
    

    您可以在此处阅读文档:http://mongoosejs.com/docs/guide.html,位于“静态”部分。还有其他更好的方法可以达到相同的结果,但这会让你开始。

    【讨论】:

    • 非常感谢。我真的不知道我的代码发生了什么,几个月来我一直在为这些函数使用 module.exports 并且从来没有遇到过问题,除了今天它突然停止工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多