在创建具有嵌套对象(例如,对象数组)的文档时,每个对象都有自己的_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
对象都被赋予.id . 这似乎有点过分并使文档膨胀,但MongoDB(或Mongoose)是否需要该文档来包含这些附加信息?如果没有,我想阻止它发生,以便唯一的_id在根文档上 .
此外,Mongoose会自动为 _id
创建一个虚拟 id
,这是我需要的,因为我的客户端代码需要一个字段 id
. 这就是我使用JSON返回虚拟的原因 . 但是,因为整个文档中都有 _id
个字段,而不仅仅是根目录,所以这个虚拟副本全部复制 . 如果无法阻止其他_id字段,如何才能使虚拟仅应用于根文档_id?或者,如果有更好的方法来做我正在尝试做的事情,它会是什么?
2 回答
我已经想出了一种方法,可以用相同的技术解决这两个问题:为每个嵌套对象类型使用显式模式,并将
_id
和id
选项设置为false
. 似乎在嵌套定义"inline"的对象时,Mongoose会在幕后为每个对象创建模式 . 由于架构的默认值为_id: true
和id: true
,因此它们将获得_id
以及具有虚拟id
. 但是通过使用显式模式覆盖它,我可以控制_id
创建 . 更多代码,但我得到了我想要的东西:@neverfox感谢您的信息,我只是添加了Nodejs的代码