如果您有子文档数组,Mongoose会自动为每个子文档数组创建id。例子:

{
    _id: "mainId"
    subDocArray: [
      {
        _id: "unwantedId",
        field: "value"
      },
      {
        _id: "unwantedId",
        field: "value"
      }
    ]
}

是否有一种方法告诉猫鼬不为数组中的对象创建id ?


当前回答

NestJS的例子,任何人寻找一个解决方案与装饰

@Schema({_id: false})
export class MySubDocument {
    @Prop()
    id: string;
}

下面是来自Mongoose Schema Type定义的id和_id的一些附加信息:

/**
* 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;

其他回答

我使用的是猫鼬4.6.3,我所要做的就是在模式中添加_id: false,不需要做一个子模式。

{
    _id: ObjectId
    subDocArray: [
      {
        _id: false,
        field: "String"
      }
    ]
}

NestJS的例子,任何人寻找一个解决方案与装饰

@Schema({_id: false})
export class MySubDocument {
    @Prop()
    id: string;
}

下面是来自Mongoose Schema Type定义的id和_id的一些附加信息:

/**
* 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: false来抑制它。

{
   sub: {
      property1: String,
      property2: String,
      _id: false
   }
}

您可以创建没有模式的子文档,并避免_id。只需在子文档声明中添加_id: false。

var schema = new mongoose.Schema({
   field1: {
      type: String
   },
   subdocArray: [{
      _id: false,
      field: { type: String }
   }]
});

这将防止在子文档中创建_id字段。

在Mongoose v5.9.10中测试

你可以用其中任何一个

var subSchema = mongoose.Schema({
//subschema fields    

},{ _id : false });

or

var subSchema = mongoose.Schema({
//subschema content
_id : false    

});

在使用第二个选项之前检查一下你的猫鼬版本