In my main file server.js I have following function:
server.js
const mongoose = require('mongoose');
const SmallRounds = require('./models/smallrounds.js');
function initRound(){
logger.info('Initializing round...');
SmallRounds.getLatestRound((err, data) => {
[...]
});
}
the function getLatestRound() gets exported in my mongoose model 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)
});
}
But when I call initRound() I get following error:
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
Why is this happening? I don't think that I have circular dependencies and have not misspelled anything. Thanks :)
That's not how you add methods to Mongoose models/schemas.
Try this:
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);
You can read the documentation here: http://mongoosejs.com/docs/guide.html, in the section "Statics". There are other, better ways of achieving the same result, but this will get you started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With