mongoDB에서 투영을 사용하여'추가'필드를 제거하는 작업 과정

7605 단어 mongodb초과필드

소개


실제 개발 과정에서 개발자의 포지셔닝 문제에 편리하도록 여러 개의 추가 필드가 존재한다.예를 들어createdAt, updatedAt 필드를 추가하여 데이터의 생성과 변경 시간을 확인합니다.클라이언트에게는 존재를 알 필요가 없다.상기 상황에 대하여 본고는 "추가"필드의 용도와 처리 과정을 상세하게 소개하였다.
기술 창고
  • mongodb 4.0.20
  • mongoose 5.10.7
  • 1 "추가" 필드는 무엇입니까


    1.1 "추가"는 업무와 무관함을 가리킨다


    mongodb에서,collection에 저장된 필드는 업무 필드만 있는 것이 아닙니다.개발자가 문제를 포지셔닝하고 집합을 확장하기 위해 여분의 필드를 저장하는 경우도 있다.
    추가 의미는 업무와 무관하고 개발과 관련된 필드를 가리킨다.이 필드들은 사용자에게 알려질 필요는 없지만 개발 과정에서 매우 중요하다.

    1.2 원인 발생


    추가 필드가 생기는 원인은 다양하다.
  • 만약mongose 플러그인으로db에 데이터를 삽입하면 기본 생성_id、__v 필드
  • 소프트 삭제는 is_를 제어하여deleted 구현..
  • 2 추가 필드 분류


    추가 필드의 발생 원인은 매우 많기 때문에 이것으로 분류할 수 있다.

    2.1 _id、__v 필드


    발생 원인: mongose를 예로 들면 schema->model->entity를 통해 mongodb에 데이터를 삽입할 때 이 데이터는 기본적으로 증가합니다_id、__v 필드.
    _id 필드는 문서의 유일한 인덱스로 몬godb에서 기본적으로 생성됩니다.유형은 ObjectID입니다.mongoDB 문서는 다음과 같이 정의됩니다.

    MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.<
    __v 필드는 몬고스가 처음 만들 때 기본적으로 생성되며, 이doc의 내부 버전 번호를 나타냅니다.

    The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The versionKey option is a string that represents the path to use for versioning. The default is __v.

    2.2 createdAt, updatedAt 필드


    createdAt, updatedAt 필드는 timestamp 옵션을 통해 지정되며 형식은 Date입니다.

    The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type assigned is Date.By default, the names of the fields are createdAt and updatedAt. Customize the field names by setting timestamps.createdAt and timestamps.updatedAt.

    2.3 is_deleted 필드


    is_deleted 필드는 소프트 삭제를 실현하는 데 자주 사용하는 방식입니다.실제 업무에서 여러 가지 이유(예를 들어 삭제 후 사용자가 다시 복구를 요구하는 등)로 인해 물리적 삭제가 아닌 소프트 삭제가 자주 사용된다.
    따라서, is_deleted 필드는 현재doc의 상태를 저장합니다.is_deleted 필드가true일 때 현재 기록이 유효하다는 것을 나타냅니다.is_deleted 필드가false일 때 현재 기록이 삭제되었음을 나타냅니다.

    3 추가 필드 관련 작업


    3.1 추가 필드 생성


    _id 필드는 필수 옵션입니다. __v,createdAt,updatedAt 필드는 설정할 수 있습니다.status 필드는 s에 대응하는chema에 직접 추가됩니다.관련 schema 코드는 다음과 같습니다.
    
    isdeleted: {
     type: String,
     default:true,
     enum: [true, false],
    },
    id: {
     type: String,
     index: true,
     unqiue: true,
     default:uuid.v4(),
    }},
    {timestamps:{createdAt:'docCreatedAt',updatedAt:"docUpdatedAt"},versionKey:false});
    schema의timestamps 옵션을 설정하면createdAt과updatedAt 필드를doc에 추가할 수 있습니다.doc를 만들고 업데이트할 때 이 두 필드는 전송할 필요가 없으면 자동으로 변경됩니다.

    3.2 추가 필드 정리


    3.1을 통해 몇 가지 추가 필드를 명확하게 만들 수 있지만 클라이언트가 인터페이스를 호출하고 돌아올 때 이 필드들은 알 필요가 없다.따라서 추가 필드를 정리해야 한다.청소 방식은 투영과 필터로 나뉜다.
    query, 업데이트 인터페이스를 예로 들자.이 중query 인터페이스는 다음과 같습니다. 1, 검색 지정 필드 2, 모든 필드 조회 3, 페이지 정렬 조회.업데이트 인터페이스는 업데이트된 데이터를 업데이트하고 되돌려 주는 데 사용됩니다.
    필드를 지정해야 하는지, 콜렉션에 내장되어 있는지 여부에 따라 4가지 종류가 있습니다.이어 이 네 가지 상황을 분석했다.
    1. 지정된 필드, 인라인 없음
    2, 지정된 필드 없음, 인라인 없음
    3, 지정된 필드, 내장
    4, 지정된 필드 없음, 내장

    3.2.1 투영


    지정한 필드가 있는 것은 조회할 때 조회 필드를 지정하는 것이지 모두 되돌릴 필요가 없다는 것을 가리킨다.mongo에서 지정한 방식은 투영 (project) 입니다.mongo 공식 문서에는 다음과 같이 정의되어 있습니다.

    The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields.
    $project는 다음과 같은 3가지 작업을 수행할 수 있습니다.
    1. 포함된 필드 지정, 금지_id 필드, 새 필드 추가
    2. 이미 존재하는 필드의 값 재설정
    3. 제외된 필드 지정
    우리는 단지 일에 관심을 가지기만 하면 된다.이어서 mongose에서 프로젝트에 대한 설명을 보십시오.

    When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.
    A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.
    참고:query "프로젝션"
    mongose는 투영이 모두 포함되거나 모두 제거된다고 밝혔다.포함과 제거가 동시에 존재하는 것을 허용하지 않습니다.... 때문에
    _id는 MongoDB에 기본적으로 포함되어 있으므로_id는 예외입니다.
    select project 투영 문장 구성 코드:
    
     /**
     *  
     * @param {*} stat   
     * @param {*} collection collectionName
     * @return {*}  
     */
     function addCommonSelectCond(stat,collection)
     {
     if(typeof(stat)!="object") return;
    
     stat["_id"] = 0;
     stat["__v"] = 0;
     stat["status"] = 0;
     stat["docCreatedAt"] = 0;
     stat["docUpdatedAt"] = 0;
    
     var embeddedRes = hasEmbedded(collection);
     if(embeddedRes["isEmbedded"])
     {
     for(var item of embeddedRes["embeddedSchema"])
     {
     stat[item+"._id"] = 0;
     stat[item+".__v"] = 0;
     stat[item+".status"] = 0;
     stat[item+".docCreatedAt"] = 0; 
     stat[item+".docUpdatedAt"] = 0; 
     }
     }
     return stat;
     }

    3.2.2 필터링


    findOne Andupdate, insert,query 등을 통해 되돌아오는 doc 대상 (이미 lean 또는 toObject 처리) 은 데이터베이스의 실제 상태입니다.따라서doc 필터와 내장 문서 필터를 포함하여 생성된doc에 대한 필터가 필요합니다.
    
    /**
     *  
     * @param {*} collection  
     * @param {*} doc  
     * @returns doc  
     */
    static clearDoc(collection,doc){
     if(doc === undefined || doc === null || typeof doc != "object" ) return null;
     doc = this.clearExtraField(doc);
    
     var res = hasEmbedded(collection);
     if(res["isEmbedded"])
     {
     let arr = res["embeddedSchema"];
     for(var item of arr){
     if(doc[item])
     doc[item] = this.clearArray(doc[item]);
     }
     }
     return doc;
    }
    
    static clearExtraField(doc){
     if(doc === null || typeof doc != "object")
     return;
     
     var del = delete doc["docCreatedAt"]&&
     delete doc["docUpdatedAt"]&&
     delete doc["_id"]&&
     delete doc["__v"]&&
     delete doc["status"];
     if(!del) return new Error(" ");
    
     return doc;
    }
    
    static clearArray(arr)
    {
     if(!Array.isArray(arr)) return;
    
     var clearRes = new Array();
     for(var item of arr){
     clearRes.push(this.clearExtraField(item));
     }
     return clearRes;
    }
    세심한 독자들은 투영과 필터의 필드 내용이 모두 추가 필드라는 것을 발견했다.그러면 어떤 상황에서 투영을 사용하고 어떤 상황에서 필터를 사용합니까?
    이 문제에 대해 필자의 건의는 추가 필드가 제거되는 것을 확보하지 못하면 이중 인증을 채택하는 것이다. 검색 전에 투영을 사용하고 검색 후에 필터를 사용하는 것이다.

    4 총결산


    본고는 실제 업무에서 종종 추가 필드가 발생한다는 것을 소개했다.한편, mongoDB에서 추가 필드를 제거하는 수단은 주로 투영, 필터이다.
    가장 빈도가 높은 쿼리 인터페이스를 예로 들면 다음과 같습니다.
    옵션 지정
    내장 옵션
    질의 전 투영
    질의 후 필터링
    지정
    내장 없음
    ×

    지정
    내장
    ×

    지정되지 않음
    내장 없음

    ×
    지정되지 않음
    내장

    ×
    따라서 필자는 schema에서options를 설정했든 안 했든 조회할 때 투영 문장을 조립하고 조회한 후에 결과 필터를 하는 것을 건의합니다.이렇게 하면 만전을 기하고,
    클라이언트에 추가 필드가 누락되지 않습니다 **.
    이 글은 몬고DB가 투영을 사용해'추가'필드를 제거한 것에 대해 소개합니다. 더 많은 관련 몬고DB가 투영으로 추가 필드를 제거한 내용은 이전의 글을 검색하거나 아래의 관련 문장을 계속 훑어보십시오. 앞으로 많은 응원 부탁드립니다!

    좋은 웹페이지 즐겨찾기