简体   繁体   English

如何在猫鼬js中嵌套相同的架构

[英]How to nest the same schema in mongoose js

I'm trying to nest schemas using mongoose js, specifically the same schema, to create a tree-like structure. 我正在尝试使用猫鼬js嵌套架构,特别是相同的架构,以创建树状结构。 In this configuration, a document can only have 1 parent, but the same document can be parent to more than one child. 在此配置中,一个文档只能有1个父级,但是同一文档可以是多个孩子的父级。 Here's how I approached it initially: 这是我最初的处理方式:

var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;

var mySchema = new Schema({
    _id: {
        type: ObjectId,
        required: true
    },
    parent: {
        _id: { 
            type: ObjectId, 
            ref: 'myModel'
        },
        required: true
    }
});

var myModel = mongoose.model('myModel', mySchema);

module.exports = {
    myModel: mongoose.model('myModel', myModel)
};

However, when I run this, I get the 但是,当我运行此程序时,我得到了

A JavaScript error occurred in the main process Uncaught Exception: TypeError: Undefined type "undefined" at "file.required" Did you try nesting Schemas? You can only nest using refs or arrays.

I must be approaching this wrong. 我一定要解决这个错误。 How do you nest the same schema using mongoose js? 如何使用猫鼬js嵌套相同的架构?

The warning already show you "You can only nest using refs or arrays.". 该警告已经显示“您只能使用引用或数组进行嵌套”。 This is a mongoose design. 这是猫鼬的设计。

But what you can do is: 但是您可以做的是:

var MySchema = new mongoose.Schema({
    objectId: String,
    parent: {
        type: mongoose.Schema.ObjectId,
        ref: 'MySchema'
    },
})

This will use a schema inside a schema, then you can use a "pre save" to update the data of your parent. 这将使用架构内的架构,然后您可以使用“预保存”来更新父级的数据。 Or you can use a array of refs and keep with only 1 element. 或者,您可以使用ref数组并仅保留1个元素。

What a do is export the schemas and not the models, so you can nest it. 要做的是导出模式而不是模型,因此您可以嵌套它。 like this: 像这样:

module.exports = MySchema;

Then I have some appModel to set the models of my collection of schemas, like this (app_model.js): 然后,我有了一些appModel来设置我的模式集合的模型,例如(app_model.js):

if(mongoose.modelNames().indexOf('mySchema') < 0) mongoose.model('mySchema', mySchema);

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

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