Nivas Dhina Nivas Dhina - 3 months ago 9
Node.js Question

Model is not a function error in postman

Iam doing basic crud operation in mongodb when i try to insert new post to db i get a message in post man as Test is not a function.

My router function is as follow.

router.route('/createtests').post(function (req, res, next) {

var Test = new Test(req.body);
postTest(Test, function (data) {

res.json({'message': 'The test created sucessfully'});

});

});

var postTest = function(test, cb){

Test.save(function(err,data){

cb(data);

});

};


My schema is as follows.

var TestSchema = common.Schema({

title : String,
testCreator : String,
datePosted : {
type: Date,
default: Date.now
},
totalQuestions : Number,
totalTime : Number,
numberOfPeopleTaking : Number,
dateOfTest : Date,
marksPerQuestions : Number,
imageUrl : String,
testType : String,

});
var Test = common.conn.model('Test', TestSchema);
console.log(typeof Test);// logging as function
console.log(Test);// logging full model with schema
module.exports = Test;


Iam getting a response as follow

{
"message": "Test is not a function",
"error": {}
}

Answer

In your function postTest , you have test with 't' and you are saving with 'T'(Test.save()) : uppercase/lowercase typo. this is what is causing your issue.

var postTest = function(test, cb){

    test.save(function(err,data){ //see the change here 'test' instead of 'Test' 

        cb(data);

    });

};

Also, change common.conn.model to common.model

var Test = common.model('Test', TestSchema);

EDIT

You are using Test as variable name and model name both. change the var to test. It should solve your issue.

router.route('/createtests').post(function (req, res, next) {

    var test = new Test(req.body); //See the change here. 'test' instead of 'Test'
    postTest(test, function (data) { //pass 'test'

        res.json({'message': 'The test created sucessfully'});

    });

});
Comments