venkat venkat - 3 months ago 48
Node.js Question

Update nested sub document using Node.js and mongoose

I tried to save details to my nested sub document

tertiary
.

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

var Tertiary = new mongoose.Schema({
title : String,
description:String,
image:String
});


The code for saving my
tertiary
data is below. I have my primary object ID as well as secondary object ID.

Todo.findById(fields.primaryid, function (err, secondary_todo) {
if (!err) {
console.log("---Inside not errot----");
console.log(fields.secondaryRefid);

secondary_todo.secondary.findById(fields.secondaryRefid,
function (err, tertiary_todo) {
console.log("---In Secondary data----");
console.log(tertiary_todo);
if (!err) {
tertiary_todo.tertiary.push({
_id: mongoose.Types.ObjectId(),
title : fields.title,
image : fields.file,
description : fields.description,
});
}
tertiary_todo.save();
});
}
});


The error I got in my terminal is


/......./.../..../lib/utils.js:419
throw err;
^
TypeError: Object [object Object],[object Object],[object Object] has no method 'findById'
at Promise.<anonymous>



Can anybody give a quick fix. I tried and struck with it.

Answer

You may want to read this page in the docs describing sub docs and also the special id() method used to find a sub document give its id.
So instead of calling findById on the sub documents

secondary_todo.secondary.findById(fields.secondaryRefid, function (err, tertiary_todo) {  ...

use id like so

var tertiary_todo = secondary_todo.secondary.id(fields.secondaryRefid);
...

Update: Another issue is probably that your schema setup is broken as you use your child schemas before they are defined. Reorder them like that

var Tertiary = new mongoose.Schema({
    title : String, 
    description:String,
    image:String
});

var Secondary = new mongoose.Schema({
    title : String,
    image:String,
    bgimage:String,
    tertiary :[Tertiary]
});

module.exports = mongoose.model('Todo', {
    title : String,
    image:String,
    bgimage:String,
    secondary:[Secondary]
});
Comments