Reputation: 6057
I am using mongoose to connect to an MongoLab database, I have separated my database model and stuff as a separate module form the rest of my code. I am trying to create an new Model and then save it to the database. unfortunately, it keeps throwing an error: TypeError: undefined is not a function
var mongoose = require('mongoose');
module.exports = (function() {
var database = {};
database.Schema = mongoose.Schema,
ObjectID = database.Schema.ObjectID;
database.Task = new database.Schema({
task: String,
});
database.Tasks = mongoose.model('Tasks', database.Task);
return database;
});
var express = require('express');
var database = require('./database');
var router = express.Router();
router.get('/', function(req, res) {
res.render('../views/index.jade', {title: 'TODO'});
});
router.post('/', function(req, res) {
// res.render('../views/index.jade', {title: 'TODO', tasks: req.body.name});
var task = new database.Task(req.body.name);
task.save(function(err) {
if(!err) {
console.log('Task: ' + task + 'successfully saved!');
} else {
res.render('../views/index.jade', {title: 'Error', tasks: 'Error: ' + err});
}
});
});
module.exports = router;
I think it has to deal with the scope of database.js
but I am not to sure. How can I fix this problem?
Test
TypeError: Cannot call method 'create' of undefined
at Object.module.exports [as handle] (E:\backbone_example\include\router.js:
13:28)
at next_layer (E:\backbone_example\node_modules\express\lib\router\route.js:
103:13)
at Route.dispatch (E:\backbone_example\node_modules\express\lib\router\route
.js:107:5)
at c (E:\backbone_example\node_modules\express\lib\router\index.js:195:24)
at Function.proto.process_params (E:\backbone_example\node_modules\express\l
ib\router\index.js:251:12)
at next (E:\backbone_example\node_modules\express\lib\router\index.js:189:19
)
at next_layer (E:\backbone_example\node_modules\express\lib\router\route.js:
77:14)
at next_layer (E:\backbone_example\node_modules\express\lib\router\route.js:
81:14)
at Route.dispatch (E:\backbone_example\node_modules\express\lib\router\route
.js:107:5)
at c (E:\backbone_example\node_modules\express\lib\router\index.js:195:24)
Upvotes: 0
Views: 3455
Reputation: 2483
.save()
is a method on mongoose models, not schemas. Try:
var task = new database.Tasks(req.body.name);
task.save(...);
http://mongoosejs.com/docs/api.html#model_Model-save
Upvotes: 1