如何在Mongoose中将模式属性设置为SubDocument类型

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

本文关键字:设置 属性 SubDocument 类型 模式 Mongoose      更新时间:2023-09-26

我想这样做:

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

但是Schema似乎不是一个有效的SchemaType。

在子文档指南中,他们只给出了一个子模式放在数组内的例子,但这不是我想要做的。

var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
  children: [childSchema]
})

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

嵌入到模式本身

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