阻止Mongoose为子文档数组项创建_id属性

Atl*_*las 196 mongoose mongodb node.js subdocument

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

{
    _id: "mainId"
    subDocArray: [
      {
        _id: "unwantedId",
        field: "value"
      },
      {
        _id: "unwantedId",
        field: "value"
      }
    ]
}
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉Mongoose不为数组中的对象创建id?

thr*_*n19 247

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

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);
Run Code Online (Sandbox Code Playgroud)

  • 即使在 subSchema 集合中,或者仅在 subSchema 被用作子文档项数组的情况下,这是否会跳过 `_id` 字段?我问这个特别是因为我自己的 [问题](http://stackoverflow.com/questions/38151433/mongoose-inserts-extra-id-in-array-of-objects-corresponding-to-related-entity) 在 SO今天。 (2认同)

Joe*_*non 115

您可以创建没有架构的子文档,并避免使用_id.只需将_id:false添加到子文档声明中即可.

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

这将阻止在您的subdoc中创建_id字段.在Mongoose中测试3.8.1


wli*_*gke 42

此外,如果您使用对象文字语法来指定子架构,您也可以添加_id: false以压缩它.

{
   sub: {
      property1: String,
      property2: String,
      _id: false
   }
}
Run Code Online (Sandbox Code Playgroud)


jem*_*oii 22

我正在使用mongoose 4.6.3,而我所要做的就是在架构中添加_id:false,不需要创建子模式.

{
    _id: ObjectId
    subDocArray: [
      {
        _id: false,
        field: "String"
      }
    ]
}
Run Code Online (Sandbox Code Playgroud)


Dee*_*rma 5

您可以使用其中任何一个

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

},{ _id : false });
Run Code Online (Sandbox Code Playgroud)

或者

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

});

Run Code Online (Sandbox Code Playgroud)

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


won*_*ngz 5

NestJS 示例,适合任何寻找装饰器解决方案的人

@Schema({_id: false})
export class MySubDocument {
    @Prop()
    id: string;
}
Run Code Online (Sandbox Code Playgroud)

以下是 Mongoose 模式类型定义中 和 的一些附加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;
Run Code Online (Sandbox Code Playgroud)