在创建具有嵌套对象(例如,对象数组)的文档时,每个对象都有自己的_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
Run Code Online (Sandbox Code Playgroud)
在最终创建文档时,数组中的lists每个allocation对象都被赋予_id,就像lists.allocations数组中的每个对象一样.这似乎有点过分并使文档膨胀,但MongoDB(或Mongoose)是否需要该文档来包含这些附加信息?如果没有,我想阻止它发生,以便唯一的_id在根文档上.
此外,Mongoose会自动创建一个虚拟idfor _id,因为我的客户端代码需要一个字段id.这就是我使用JSON返回虚拟的原因.但是,因为_id整个文档中都有字段,而不仅仅是根目录,所以这个虚拟副本全部复制.如果无法阻止其他_id字段,我如何才能将虚拟仅应用于根文档_id?或者,如果有更好的方法来做我正在尝试做的事情,它会是什么?
nev*_*fox 15
我已经想出了一种方法,可以使用相同的技术解决这两个问题:为每个嵌套对象类型使用显式模式,并将它们_id和id选项设置为false.似乎在嵌套定义"内联"的对象时,Mongoose会为幕后的每个对象创建模式.由于架构的默认值是_id: true和id: true,它们将获得_id一个虚拟的id.但是通过使用显式模式覆盖它,我可以控制_id创建.更多代码,但我得到了我想要的:
mongoose = require "mongoose"
Schema = mongoose.Schema
AllocationSchema = new Schema
allocation:
type: Number
required: true
,
_id: false
id: false
mongoose.model "Allocation", AllocationSchema
ListsSchema = new Schema
list:
type: Schema.Types.ObjectId
required: true
ref: "List"
allocations: [AllocationSchema]
,
_id: false
id: false
mongoose.model "Lists", ListsSchema
PortfolioSchema = new Schema
name:
type: String
required: true
unique: true
trim: true
lists: [ListsSchema]
createdAt:
type: Date
default: Date.now
updatedAt:
type: Date
Run Code Online (Sandbox Code Playgroud)
@neverfox 感谢您提供信息,我只是添加了 Nodejs 的代码
var _incidents = mongoose.Schema({
name : {type : String},
timestamp: {type : Number},
_id : {id:false}
});
_schema = mongoose.Schema({
_id: {type: String, required: true},
user_id: {type: String, required: true},
start_time: {type: Number, required: true},
incidents : [_incidents],
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9290 次 |
| 最近记录: |