【问题标题】:How do you set a schema property to be of type SubDocument in Mongoose?如何在 Mongoose 中将模式属性设置为 SubDocument 类型?
【发布时间】:2015-08-21 09:27:28
【问题描述】:

我想做这样的事情:

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

但似乎 Schema 不是有效的SchemaType

在子文档guide 中,他们只给出了一个将子架构放在数组内的示例,但这不是我想要做的。

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

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

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    看起来您只是想为每个属性创建一个子对象。您可以通过以下两种方式之一来完成。

    嵌入架构本身

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

    在多个模式中使用的可重用对象

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

    【讨论】:

    • 我之前尝试过方法 1(方法 2 不是我想要做的)。我遇到了this 问题,正在寻找替代方案。我希望如果我使用 localSchema,我可以使用 require: true 并让它按我期望的方式工作。
    猜你喜欢
    • 2017-05-13
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2010-11-03
    相关资源
    最近更新 更多