使用Node.js和mongoose更新嵌套的子文档

时间:2016-08-08 05:13:51

标签: node.js mongodb mongoose

我尝试将详细信息保存到嵌套的子文档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
});

保存我的tertiary数据的代码如下。我有我的主对象ID以及辅助对象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();
        }); 
    }
});

我在终端中收到的错误是

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

任何人都可以快速解决问题。我试着用它来打击它。

1 个答案:

答案 0 :(得分:2)

您可能需要阅读描述子文档的文档中的this页面,以及用于查找子文档的特殊id()方法,并提供其ID。
因此,不要在子文档上调用findById

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

像这样使用id

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

更新:另一个问题可能是您的架构设置在您定义之前使用子架构时已损坏。像那样重新排序

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