MongoDB,特别是 mongoose.js,允许元组作为属性。例如,MongoDB documentation has this example其中属性 comments
本身就是一个具有属性 [{body: String, date: Date}]
的对象数组。耶!
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
})
现在,当我将其保留到 MongoDB 时,不仅 blogSchema
的每个实例都会获得自己的 _id 值(例如 502efea0db22660000000002
),而且 的每个单独值comment
拥有自己的 _id
字段。
在大多数情况下,我不在乎,但在我的应用程序中,comments
的模拟可能有数千个值。每个都有自己巨大的 _id
值。
我可以阻止这种情况发生吗?我永远不需要单独提及它们。或者我应该学会停止担心并喜欢这个唯一的标识符?我从小就对 Vic20 和 TRS80 进行编程,因此可能对浪费内存/存储过于偏执。
最佳答案
可以通过将 noId
架构选项设置为 true
来禁用 _id
。要传递该选项,您需要传递模式实例,而不是使用对象文字:
// instead of this...
comments: [{ body: String, date: Date }]
// do this...
var commentSchema = new Schema({ body: String, date: Date }, { noId: true });
var blogSchema = new Schema({
..
comments: [commentSchema]
})
关于mongodb - 元组(数组)作为 mongoose.js 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015429/