2017-10-07 217 views
2

在我的主文件server.js我有以下功能:Node.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 is not a function

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

这究竟是为什么?我不认为我有循环依赖关系,没有任何拼写错误。谢谢:)

+0

也许'mongoose.model'中返回的对象被冻结或者什么?确保您要求的文件与本文中的完全相同。 – MinusFour

+0

这是,我复制粘贴代码 –

回答

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,在部分 “静”。还有其他更好的方法来达到同样的效果,但这会让你开始。

+0

巨大的谢谢你。我真的不知道我的代码发生了什么,我几个月来一直在使用module.exports来完成这些功能,除了今天突然停止工作以外,从来没有遇到过问题。 –

相关问题