如果您有子文档数组,Mongoose 会自动为每个数组创建 id。例子:
{
_id: "mainId"
subDocArray: [
{
_id: "unwantedId",
field: "value"
},
{
_id: "unwantedId",
field: "value"
}
]
}
有没有办法告诉 Mongoose 不要为数组中的对象创建 id?
这很简单,您可以在 subschema 中定义它:
var mongoose = require("mongoose");
var subSchema = mongoose.Schema({
// your subschema content
}, { _id : false });
var schema = mongoose.Schema({
// schema content
subSchemaCollection : [subSchema]
});
var model = mongoose.model('tablename', schema);
您可以创建没有架构的子文档并避免 _id
。只需将 _id: false
添加到您的子文档声明中。
var schema = new mongoose.Schema({
field1: {
type: String
},
subdocArray: [{
_id: false,
field: { type: String }
}]
});
这将阻止在您的子文档中创建 _id
字段。
在 Mongoose v5.9.10
中测试
此外,如果您使用对象文字语法来指定子模式,您也可以只添加 _id: false
来抑制它。
{
sub: {
property1: String,
property2: String,
_id: false
}
}
我正在使用 mongoose 4.6.3,我所要做的就是在模式中添加 _id: false ,无需创建子模式。
{
_id: ObjectId
subDocArray: [
{
_id: false,
field: "String"
}
]
}
_id
是一个字段而不是一个约束。
_id = mongoose.Types.ObjectId()
,那么该 _id 在集合中是否是唯一的?
您可以使用其中任何一个
var subSchema = mongoose.Schema({
//subschema fields
},{ _id : false });
或者
var subSchema = mongoose.Schema({
//subschema content
_id : false
});
在使用第二个选项之前检查你的猫鼬版本
如果您想使用预定义的模式(带 _id)作为子文档(不带 _id),理论上可以执行以下操作:
const sourceSchema = mongoose.Schema({
key : value
})
const subSourceSchema = sourceSchema.clone().set('_id',false);
但这对我不起作用。所以我补充说:
delete subSourceSchema.paths._id;
现在我可以在没有 _id 的情况下在我的父文档中包含 subSourceSchema。我不确定这是不是干净的方法,但它有效。
NestJS 示例,适用于任何寻找装饰器解决方案的人
@Schema({_id: false})
export class MySubDocument {
@Prop()
id: string;
}
以下是来自 id
和 _id
的 Mongoose 架构类型定义的一些附加信息:
/**
* Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field
* cast to a string, or in the case of ObjectIds, its hexString.
*/
id?: boolean;
/**
* Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema
* constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you
* don't want an _id added to your schema at all, you may disable it using this option.
*/
_id?: boolean;
不定期副业成功案例分享
_id
字段,或者仅在使用 subSchema 嵌入为子文档项数组的情况下?我之所以这么问,是因为我今天在 SO 上的question。{ _id: false }
,子模式的两个级别都没有 id。有什么办法可以解决这种行为?{ _id : true }
?let studentSchema = new Schema({ studentId: { type: ObjectId, ref: Student.modelName }, performance: [performanceSchema] }, { _id: false });
更改为这个:let studentSchema = new Schema({ _id: false, id: false, studentId: { type: ObjectId, ref: Student.modelName }, performance: [performanceSchema] });
并且停止在studentSchema
上创建_id
,但保留在performance
子文档数组中的对象上创建_id
。不确定是否需要_id: false
和id: false
。