Node.js | TypeError:不是一个函数

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

server.js

const mongoose = require('mongoose'); const SmallRounds = require('./models/smallrounds.js'); function initRound(){ logger.info('Initializing round...'); SmallRounds.getLatestRound((err, data) => { [...] }); } 

函数getLatestRound()在我的mongoose模型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)
at 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模型/模式。

尝试这个:

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