我在 MongoDB 中有一些如下所示的数据:
{
name: "Steve",
location: {
city: "Nowhere, IL",
country: "The United States of Awesome"
}
}
我使用对象来组织常见的数据结构(如位置),在 Mongoose 中可能很好地映射到模式。不幸的是,它们似乎并没有真正在 Mongoose 中工作。
如果我只是嵌入一个对象,像这样:
{
name: String,
location: {
city: String,
country: String
}
}
它似乎可以工作,但表现出一些奇怪的行为,给我带来了问题(例如,instance.location.location
返回 location
,并且子对象从父模式继承方法)。我 started a thread在 Mongoose 列表中,但它没有看到任何 Action 。
如果我嵌入一个 Schema,像这样:
{
name: String,
location: new Schema({
city: String,
country: String
})
}
...我的应用程序没有启动(Schema
不是 Mongoose 支持的类型)。同理
{
name: String,
location: Object
}
……无论如何,这并不理想。
我是否遗漏了什么,或者我的架构与 Mongoose 不兼容?
最佳答案
我做了类似的事情:
var Topic = new Schema({
author : ObjectId
, title : String
, body : String
, topics : [Topic]
});
这在我的测试中运行良好。但是,移除阵列支架会导致错误。对我来说似乎是一个错误。
https://github.com/LearnBoost/mongoose/blob/master/lib/mongoose/schema.js#L185
转储类型,我只得到 String、Number、Boolean、DocumentArray、Array、Date、ObjectId、Mixed——这似乎是故意的,schema/index.js 看起来不像是动态注册新 Schema 到类型列表,所以我猜这还不是受支持的用例。
https://github.com/LearnBoost/mongoose/issues/188
“嵌入单个文档是不可能的。这不是一个好主意(只需使用常规嵌套对象)”
乔什
关于mongodb - Mongoose 是否只支持数组中的嵌入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171820/