programing

Mongoose가 하위 문서 배열 항목에 대한 _id 속성을 만들지 못하도록 합니다.

yellowcard 2023. 3. 11. 08:48
반응형

Mongoose가 하위 문서 배열 항목에 대한 _id 속성을 만들지 못하도록 합니다.

하위 문서 배열이 있는 경우 Mongoose는 각 배열에 대한 ID를 자동으로 생성합니다.예:

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

Mongoose에게 어레이 내의 오브젝트 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 }
   }]
});

이로 인해, E-메일 주소의 작성은 방지됩니다._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"
      }
    ]
}

어느쪽이든 사용하실 수 있습니다.

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

},{ _id : false });

또는

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

});

두 번째 옵션을 사용하기 전에 mongoose 버전을 확인하십시오.

사전 정의된 스키마(_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;
}

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;

언급URL : https://stackoverflow.com/questions/17254008/stop-mongoose-from-creating-id-property-for-sub-document-array-items

반응형