简体   繁体   English

如何在Mongoose中将架构属性设置为SubDocument类型?

[英]How do you set a schema property to be of type SubDocument in Mongoose?

I want to do something like this: 我想做这样的事情:

var userSchema = new Schema({
  local: localSchema,
  facebook: facebookSchema,
  twitter: twitterSchema,
  google: googleSchema
});

But it seems that a Schema is not a valid SchemaType . 但是似乎Schema不是有效的SchemaType

In the SubDocuments guide , they only give an example where the child schema is put inside of an array, but that isn't what I want to do. 在SubDocuments 指南中 ,他们仅提供一个示例,其中将子架构放在数组中,但这不是我想要的。

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  children: [childSchema]
})

It looks like you're just trying to create a sub object for each of those properties. 看来您只是想为每个属性创建一个子对象。 You can accomplish this one of two ways. 您可以通过以下两种方法之一来完成此操作。

Embedded in the schema itself 嵌入模式本身

var userSchema = new Schema({
    local: {
        someProperty: {type: String}
        //More sub-properties...
    }
    //More root level properties
});

Reusable object to be used in multiple schemas 可在多个架构中使用的可重用对象

//this could be defined in a separate module and exported for reuse
var localObject = {
    someProperty: {type: String}
    //more properties
}

var userSchema = new Schema({
    local: localObject
});

var someOtherSchema = new Schema({
    test: localObject
});

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

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