venkat venkat - 4 months ago 26
Node.js Question

updating subdocument mongoose and nodejs

I need to save my secondary details . This is my nodejs model .

var mongoose = require('mongoose');
module.exports = mongoose.model('Todo', { title : String,
image:String,
bgimage:String,
secondary:[Secondary]
});
var Secondary = new mongoose.Schema({
title : String,
image:String,
bgimage:String,
tertiary :[Tertiary]
});


My code in Nodejs controller to save

Todo.findById(fields.primaryid, function (err, secondary) {
if (!err) {
Todo.secondary.push({ title : fields.title,
image : fields.file,
bgimage : fields.bgfile,
});
Todo.save();
}
});


But in my console following error occur:


TypeError: Cannot call method 'push' of undefined


How to fix this. I have already seen many queries related this .But nothing help me

Answer

I found the error in your code, replace it with mine and hope it will work fine

Todo.findById(fields.primaryid, function (err, secondary_todo) {
if (!err) {
secondary_todo.secondary.push({ title : fields.title,
        image : fields.file,
        bgimage : fields.bgfile,
         });
secondary_todo.save();
}});