简体   繁体   中英

Node.js | TypeError: […] is not a function

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.

I was using upper-case module, and getting error TypeError: upperCase is not a function l

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

as every tutorial written in this way.

I changed it to

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

and working fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM