创建包含嵌套对象(例如对象数组)的文档时,每个对象都有自己的_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
对象也是如此.这似乎是对文档的过度杀戮和inflating ,但MongoDB(或Mongoose)是否有理由需要文档包含这些附加信息?如果没有,我想阻止它发生,这样唯一的_id就在根文档上.
此外,Mongoose会自动为_id
创建一个虚拟的id
,我需要它,因为我的客户机代码需要一个字段id
.这就是为什么我要用JSON返回virtuals.然而,由于整个文档中有_id
个字段,而不仅仅是根字段,所以这个虚拟字段复制了all个字段.如果没有办法阻止附加的_id字段,我如何才能让虚拟文档只应用于根文档_id?或者如果有更好的方法来做我想用它做的事情,那会是什么?