简体   繁体   English

猫鼬嵌套模式

[英]Mongoose nested schema

I want to make a system of topics. 我想建立一个主题系统。 each topic may have subtopics which are also topics. 每个主题都可以具有子主题,这些子主题也是主题。 meaning the subtopics may also have subtopics. 意味着子主题也可能有子主题。 for example example image 例如示例图片

I tried to create a topic schema and add a subtopic field which will ref to topic schema too. 我试图创建一个主题架构并添加一个子主题字段,该字段也将引用主题架构。 cant seem to get this working my schema code: 我的模式代码似乎无法正常工作:

const mongoose = require('mongoose');

const TopicSchema = new mongoose.Schema({
    name: {type:String,unique:true},
    sub_topic:[{type:mongoose.Schema.Types.ObjectId, ref : 'Topic'}] 
});

const Topic =mongoose.model('Topic', TopicSchema);
module.exports = Topic;

Also what the data im sending to the server should look like to make a new instance? 即时消息发送到服务器的数据应该看起来像什么来创建新实例? and on the server how do i save it? 在服务器上如何保存?

i try to save like this now : const topic = new Topic(); 我现在尝试像这样保存:const topic = new Topic();

topic.name = req.body.name;
topic.sub_topic.name=req.body.sub_topic

and the data im sending is :(json) 我发送的数据是:(json)

{
    "name":"TestMain",
    "sub_topic":[{"name":"TestSub"}]            
}

UPDATE : got this done using a recursive function. 更新:使用递归函数完成此操作。

function subtopicHandler(topic, sub_topic) {
    Topic.find({
      "name": topic.name
    }, function (err, res) {
      if (err) throw err
      return;
    })

    if (sub_topic == undefined) {
      let ntopic = new Topic();
      ntopic.name = topic.name;
      ntopic.sub_topic == undefined;
      ntopic.save(function (err, result) {
        if (err) console.log('saving err', err)
      });
      return ntopic._id;
    }
    let mainTopic = new Topic();
    mainTopic.name = topic.name;
    sub_topic.forEach(function (sub) {
      mainTopic.sub_topic.push(subtopicHandler(sub, sub.sub_topic));
    })
    var retME;
    mainTopic.save(function (err, result) {
      if (err) {
        console.log('saving err', err)
        throw err;
      }
    });
    return mainTopic._id;

  }

Using this schema : 使用此架构:

const TopicSchema = new mongoose.Schema({
    name: {type:String,unique:true},
    sub_topic:[{type:mongoose.Schema.Types.ObjectId, ref : 'Topic'}] 
});

and data sent as : 数据发送为:

{
    "name":"A",
    "sub_topic":[
                    {"name":"C","sub_topic":
                        [
                            {"name":"C1"}
                            ,
                            {"name":"C2"}
                        ]
                    }
                    ,
                    {"name":"B"}
                    ,
                    {"name":"D","sub_topic":
                        [
                            {"name":"D1"}
                            ,
                            {"name":"D2"}
                            ,
                            {"name":"D3"}
                        ]
                    }
                ]            
}

to the API endpoint handled this way: API端点以这种方式处理:

let mainTopic = new Topic();
    mainTopic.name = req.body.name;
    subtopicHandler(mainTopic, req.body.sub_topic);
  })

If you are sending following json 如果您正在发送以下json

const obj = {
    "name":"TestMain",
    "sub_topic":[{"name":"TestSub"}]            
}

Then, 然后,

let mainTopic = new Topic();
let subTopic = new Topic();

// assuming for now you have only one sub-topic in array
subTopic.name = obj[0].name;

subTopinc.save(function(err,result)=>{
    if(!err){
        mainTopic.name = obj.name;
        mainTopic.sub_topic = [result._id]
        mainTopic.save(function(err,result){
            console.log(result);
        })
    }
});

From you schema definition and the given json you can follow the above step to get the results. 从您的架构定义和给定的json中,您可以按照上述步骤获取结果。

Hope this will help you. 希望这会帮助你。

You can do this with sub docs check out the documentation. 您可以使用子文档来执行此操作,以查看文档。

https://mongoosejs.com/docs/subdocs.html https://mongoosejs.com/docs/subdocs.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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