简体   繁体   中英

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

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();
}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM