Joe Berthelot
Joe Berthelot

Reputation: 735

Mongoose .save is not a function

JS:

var express = require('express');
var router = express.Router();

// Mongoose
var mongoose = require('mongoose');
var mongoosedb = 'DBURL';
mongoose.connect(mongoosedb);

var database = mongoose.connection;
database.on('error', console.error.bind(console, 'connection error:'));
database.once('open', function() {
  console.log('Mongoose is connected.');
});

var taskSchema = mongoose.Schema({
    name: String,
    isDone: Boolean
});

var Tasks = mongoose.model('Tasks', taskSchema);

// Get all tasks
router.get('/tasks', function(req, res, next) {
  Tasks.find(function(err, tasks) {
    if(err) {
      console.log('error');
      res.send(err);
    }
    res.json(tasks);
  });
});

// Get single task
router.get('/task/:id', function(req, res, next) {
  Tasks.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, task) {
    if(err) {
      res.send(err);
    }
    res.json(task);
  });
});

// Save task
router.post('/task', function(req, res, next) {
  var task = req.body;
  if(!task.title || !(task.isDone + '')) {
    res.status(400);
    res.json({
      "error": "Bad Data"
    });
  } else {
    task.save(function(err, task) {
      if(err) {
        res.send(err);
      }
      res.json(task);
    })
  }
});

// Delete task
router.delete('/task/:id', function(req, res, next) {
  Tasks.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, task) {
    if(err) {
      res.send(err);
    }
    res.json(task);
  });
});

// Update task
router.put('/task/:id', function(req, res, next) {
  var task = req.body;
  var updTask = {};

  if (task.isDone) {
    updTask.isDone = task.isDone;
  }

  if (task.title) {
    updTask.title = task.title;
  }

  if (!updTask) {
    res.status(400);
    res.json({
      "error": "Bad Data"
    });
  } else {
    task.update({_id: mongojs.ObjectId(req.params.id)}, updTask, {}, function(err, task) {
      if(err) {
        res.send(err);
      }
      res.json(task);
    });
  }
});

module.exports = router;

I'm simply just trying to add a record to MongoDB using Mongoose.

After some Googling I couldn't find answer. My .find and .findOne methods work fine but for some reason I get the error task.save is not a function. What am I doing wrong?

Upvotes: 1

Views: 3369

Answers (2)

twk
twk

Reputation: 1841

I think your task creation is being done incorrectly.

First go ahead and import your model up at the top with your dependencies so we can access the model methods directly:

var express = require('express');
var router = express.Router();

// Mongoose
var mongoose = require('mongoose');
var mongoosedb = 'DBURL';
var Task = require('mongoose').model('Task');  // add your Task model

Then, in your save a task code, change it to this:

// Save task
router.post('/task', function(req, res, next) {
  var task = new Task(req.body) // See http://mongoosejs.com homepage demo example for basic creation
  if(!task.title || !(task.isDone + '')) {
    res.status(400);
    res.json({
      "error": "Bad Data"
    });
  } else {
    task.save(function(err, task) {
      if(err) {
        res.send(err);
      }
      res.json(task);
    })
  }
});

As your current Task creation is setup, you're just setting it to the req.body contents but not actually initializing an instance via the mongoose methods.

I personally like to use mongoose promises instead, just because I tend to like the style more. But you could also do something like this, if you have given access to your Task model via grabbing it as a dependency (as shown above):

Task.create(req.body)
    .then(function(newTask) {
        console.log("Task created successfully.");
        return res.json(newTask);  // using res.json here
    })
    .catch(function(err) {
        console.log("There was a problem creating task.");
        return res.status(500).json(err); // sends status with json obj
    })

Anyhow, I hope this helps, let me know if this works, if not I'll check back later and see!

Upvotes: 2

Bertrand Martel
Bertrand Martel

Reputation: 45503

Your variable task is the body object you have defined previously :

var task = req.body;

If you want to generate a Tasks document from it, use :

var newTask = new Tasks(task);
newTask.save(function(err, task) {
    if (err) {
        res.send(err);
    }
    res.json(task);
});

Check mongoose Models documentation

You have also confused task.update with Tasks.update

Upvotes: 2

Related Questions