【发布时间】:2013-05-28 17:22:31
【问题描述】:
当创建包含嵌套对象的文档(例如对象数组)时,每个对象都有自己的 _id。例如,我的架构如下所示:
mongoose = require "mongoose"
Schema = mongoose.Schema
schema = new Schema
name:
type: String
required: true
unique: true
trim: true
lists: [
list:
type: Schema.Types.ObjectId
required: true
ref: "List"
allocations: [
allocation:
type: Number
required: true
]
]
createdAt:
type: Date
default: Date.now
updatedAt:
type: Date
# Ensure virtual fields are serialised.
schema.set "toJSON",
virtuals: true
exports = module.exports = mongoose.model "Portfolio", schema
当最终创建文档时,lists 数组中的每个对象都被赋予一个 _id,lists.allocations 数组中的每个 allocation 对象也是如此。这似乎有点矫枉过正并且使文档膨胀,但是 MongoDB(或 Mongoose)是否有理由需要文档来包含这些附加信息?如果没有,我想防止它发生,以便唯一的 _id 在根文档上。
此外,Mongoose 会自动为_id 创建一个虚拟的id,这是我需要的,因为我的客户端代码需要一个字段id。这就是为什么我使用 JSON 返回虚拟对象的原因。但是,由于整个文档中都有_id 字段,而不仅仅是在根目录,所以这个虚拟复制了它们中的所有。如果没有办法阻止额外的 _id 字段,我怎样才能获得一个仅适用于根文档 _id 的虚拟?或者,如果有更好的方法来做我想做的事情,那会是什么?
【问题讨论】: