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

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

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


这很简单,你可以在子模式中定义:

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
   }
}

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

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

你可以用其中任何一个

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

},{ _id : false });

or

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;

现在我可以包括subSourceSchema在我的父文档没有_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;