如何使用猫鼬更新使用递归模型创建的对象

时间:2020-08-23 10:50:43

标签: node.js mongodb mongoose

我正在尝试更新使用递归模型创建的子文档。我可以通过指定完整路径来更新它,但是我想直接访问和更新该子文档。我将不胜感激。

  const mongoose = require('mongoose');

  const express = require('express');

  mongoose. connect("mongodb://localhost:27017/recursive", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false,
    }).then(() => console.log("DB connection successful!"));

    Schema = mongoose.Schema;

    var Tasks = new Schema({
      title     : String,
      duration  : Number
    });

    Tasks.add({
        subtasks  : [Tasks]
    });

    const Project = mongoose.model("Project", Tasks);


    function add(){

       project = new Project({title:"task level 1", duration:10,
                   subtasks:[{title:"task level 2", duration:20,
                   subtasks:[{title:"task level 3", duration:30,
                   subtasks:[{title:"task level 4", duration:100
      }]}]}]});

       project.save()
    }


    function update(id){

      Project.findByIdAndUpdate(id,{$set:{"subtasks.0.subtasks.0.subtasks.0.title":"zzz"}},
        null, function (err, result) {
        if (err) {
          console.log(err);
        } else {
          console.log(result);
        }
      });
    }

0 个答案:

没有答案