node.js Mongoose 中的嵌套数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11342073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested arrays in Mongoose
提问by JuCachalot
In the collection I'm working on, a document looks like this:
在我正在处理的集合中,文档如下所示:
{
name: 'Myname',
other: 'other',
stuff: [
['something', 12, 4, 'somethingelse'],
['morestuff', 2, 4, 8],
['finally', 12, 'again', 58],
]
}
I wrote this Mongoose schema to access it:
我写了这个 Mongoose 模式来访问它:
var MyDocSchema = new Schema({
name: String,
other: String,
stuff: [],
});
When I query a doc, everything works well, the output shown in the console is right. But when, I try to do console.log(myDoc.stuff), I got the following:
当我查询文档时,一切正常,控制台中显示的输出是正确的。但是,当我尝试执行 console.log(myDoc.stuff) 时,我得到以下信息:
['something', 12, 4, 'somethingelse', 'morestuff', 2, 4, 8, 'finally', 12, 'again', 58]
instead of
代替
[
['something', 12, 4, 'somethingelse'],
['morestuff', 2, 4, 8],
['finally', 12, 'again', 58],
]
What am I doing wrong? Thank you for your help!!
我究竟做错了什么?感谢您的帮助!!
回答by Hugo
Disclaimer: This response is pretty dated, 2012! It might not be the most accurate.
免责声明:此回复非常过时,2012 年!它可能不是最准确的。
From the Mongoose documentation.
来自猫鼬文档。
http://mongoosejs.com/docs/schematypes.html: Scroll down to the Array section:
http://mongoosejs.com/docs/schematypes.html:向下滚动到 Array 部分:
Note: specifying an empty array is equivalent to
[Mixed]. The following all create arrays ofMixed.
注意:指定一个空数组等效于
[Mixed]. 以下都创建了Mixed.
Details on what that means is in the Mixed section right above the Array section.
有关这意味着什么的详细信息,请参见 Array 部分正上方的 Mixed 部分。
Here's what you need to do.
这是您需要做的。
Define a schema for the embedded documents:
为嵌入的文档定义架构:
var Stuff = new Schema({
name: String,
value1: Number,
...
});
Use that instead of an empty array []:
使用它而不是空数组[]:
var MyDocSchema = new Schema({
name: String,
other: String,
stuff: [Stuff],
});

