Gustavo Mendonça Gustavo Mendonça - 23 days ago 7
Node.js Question

save is not a function

I need to insert a 'caso' in my db but I get an error saying that

caso.save is not a function
. I already tried a thousands of different ways to insert and none worked. Am I doing something wrong?

PS: My
caso.find(...)
is working fine!

The server side code:

app.post('/api/casos', function (req, res) {
var caso = new Caso();
caso = req.body;

caso.save(function (err) {
if (err) {
res.send(err);
} else {
res.json({message: "Caso adicionado com sucesso!"});
}
});
});


The controller code:

$http.post('/api/casos', $rootScope.caso).success(function(res){
console.log(res);
});


My 'caso' model:

var mongoose = require('mongoose');

module.exports = mongoose.model('Caso', {
caso: Number,
doenca: String,
areaDamaged: String,
cankerLesion: String,
cropHist: String,
date: String,
externalDecay: String,
fruitSpots: String,
fruitingBodies: String,
fruitPods: String,
germination: String,
hail: String,
intDiscolor: String,
leafMalf: String,
leafMild: String,
leafShread: String,
leafspotsHalo: String,
leafspotSize: String,
leafspotsMarg: String,
leaves: String,
lodging: String,
moldGrowth: String,
mycelium: String,
plantGrowth: String,
plantStand: String,
precip: String,
roots: String,
sclerotia: String,
seed: String,
seedDiscolor: String,
seedSize: String,
seedTmt: String,
severity: String,
shriveling: String,
stem: String,
stemCankers: String,
temp: String
}, "casos");


The req.body JSON:

{ areaDamaged: 'low-areas',
cankerLesion: 'dk-brown-blk',
cropHist: 'same-1st-yr',
date: 'Abril',
externalDecay: 'Absent',
fruitSpots: 'dna',
fruitingBodies: 'Absent',
fruitPods: 'dna',
germination: '90-100%',
hail: 'Yes',
intDiscolor: 'None',
leafMalf: 'Absent',
leafMild: 'Absent',
leafShread: 'absent',
leafspotsHalo: 'absent',
leafspotSize: 'dna',
leafspotsMarg: 'dna',
leaves: 'Abnorm',
lodging: 'Yes',
moldGrowth: 'Absent',
mycelium: 'Absent',
plantGrowth: 'Abnorm',
plantStand: 'lt-normal',
precip: 'Normal',
roots: 'Norm',
sclerotia: 'Absent',
seed: 'Norm',
seedDiscolor: 'Absent',
seedSize: 'Norm',
seedTmt: 'none',
severity: 'pot-severe',
shriveling: 'Absent',
stem: 'Abnorm',
stemCankers: 'below-soil',
temp: 'norm',
caso: 1,
doenca: 'phytophthora-rot' }

Answer

The save method you're trying to use is part of the Model, not your req.body. So you have to get rid of that line:

caso = req.body;

Because it's overriding that line:

var caso = new Caso();