Node.js Mongoose错误:嵌套架构

Node.js Mongoose错误:嵌套架构,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个关于筑巢猫鼬模式的问题 下面是一个简单的代码片段 var aSchema = new Schema({bar: String}); var bSchema = new Schema({a: aSchema, foo: String}); var cSchema = new Schema({as: [aSchema], foo:String}); 这将在bSchema上抛出TypeError:TypeError:Undefined type at's'尝试嵌套架构了吗?只能使用引用或数组

我有一个关于筑巢猫鼬模式的问题

下面是一个简单的代码片段

var aSchema = new Schema({bar: String});
var bSchema = new Schema({a: aSchema, foo: String});
var cSchema = new Schema({as: [aSchema], foo:String});
这将在
bSchema
上抛出
TypeError
TypeError:Undefined type at's'尝试嵌套架构了吗?只能使用引用或数组进行嵌套。
,但对于
cSchema
,嵌套效果很好


只想问一下为什么
bSchema
不起作用。在Mongoose文档中找不到解释。谢谢。

MongoDB不是关系数据库。这可能会让一些习惯于RDBS模型的人感到困惑(我仍然偶尔会被绊倒……但我真的不是一个DB人)

通常,您会发现在Mongo实体中引用其他文档是有益的。Mongoose模式提供了一种非常简单和有效的方法来实现这一点,这种方法感觉非常相关

定义将存储对不同类型文档的引用的架构时,将相关属性定义为具有
类型
ref
的对象。通常在定义模式属性时,您可以简单地说:
a:Number
;但是,Mongoose为模式属性提供了许多不同的选项,而不是类型:

a: {
   type: Number,
   required: true   
}
设置
required:true
将阻止我们在
a
属性不存在的情况下保存文档

一旦您了解了如何使用对象定义定义模式,就可以利用Mongoose的填充机制:

a: {
   type: Mongoose.Schema.ObjectId,
   ref: 'a'
}
这告诉Mongoose将特定
a
文档的
ObjectId
(Mongoose特定标识符)存储为模式的
a
属性。还跟着我吗

在Mongoose文档上设置此属性时,您可以简单地说:
doc.a=myA
。当您转到保存
doc
时,Mongoose将自动进行转换,并仅将ID存储在数据库中


检索引用其他架构的文档时,需要填充。我不想深入讨论这个问题,但它非常简单-。

我面临这个问题,因为我对MongoDB是全新的。后来我发现我们需要在猫鼬的帮助下使用如下关系

下面是我的国家模式

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var CountrySchema = new Schema({
    name: { type: String, required: true },
    activeStatus: Boolean,
    createdOn: Date,
    updatedOn: Date
});
我可以在我的状态模式中使用这个模式,如下所示

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var StateSchema = new Schema({
    name: { type: String, required: true },
    country: {type: ObjectId, ref: "Country"},
    activeStatus: Boolean,
    createdOn: Date,
    updatedOn: Date
});

在这里,我在ref

的帮助下使用指向我的另一个模式
bSchema
a
属性应该是对
aSchema
对象的引用吗?不要那样做。Do:
a:{type:Mongoose.Schema.ObjectId',ref:'a'}
其中
ref:a中的
a
是您使用
aSchema
创建的Mongoose模型的名称