programing

Mongoose의 '_v' 필드는 무엇입니까?

mbctv 2023. 3. 17. 21:54
반응형

Mongoose의 '_v' 필드는 무엇입니까?

사용하고 있다Mongoose의 버전 3MongoDB버전 2.2.나는 알아차렸다__v필드가 표시되기 시작했습니다.MongoDB문서.버전 관리와 관련이 있나요?어떻게 사용하나요?

여기서부터:

versionKey는 Mongoose에 의해 처음 작성되었을 때 각 문서에 설정된 속성입니다.이 키 값은 문서의 내부 리비전을 포함합니다.이 문서 속성의 이름은 구성할 수 있습니다.기본값은 입니다.__v.

이것이 애플리케이션과 경합하는 경우는, 다음과 같이 설정할 수 있습니다.

new Schema({..}, { versionKey: '_somethingElse' })

토니의 해답이 안 보이네그래서 내가 직접 해결해야 해


version_key가 필요 없는 경우 다음 작업을 수행할 수 있습니다.

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default: Date.now}
}, {
    versionKey: false // You should be aware of the outcome after set to false
});

versionKey를 false로 설정하면 문서가 더 이상 버전화되지 않습니다.

이것은 문서에 하위 문서의 배열이 포함되어 있는 경우 문제가 됩니다.하위 문서 중 하나를 삭제하여 배열 크기를 줄일 수 있습니다.나중에 다른 작업이 배열의 하위 문서에 원래 위치에서 액세스할 수 있습니다.

어레이가 작아졌기 때문에 어레이 내의 잘못된 서브문서에 실수로 액세스 할 수 있습니다.

versionKey는 문서를 mongoose가 올바른 컬렉션 버전에 액세스하기 위해 내부적으로 사용하는 versionKey와 관련지어 이 문제를 해결합니다.

상세한 것에 대하여는, http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html 를 참조해 주세요.

NestJ에서 제거하려면 옵션을 추가해야 합니다.Schema()데코레이터

@Schema({ versionKey: false })

필요한 경우 버전 키를 비활성화할 수 있습니다.

다음의 예를 참조해 주세요.

var User = new mongoose.Schema({
   FullName:{
       type :String,
      
   },
   BirthDay:{
       type :String,
       
   },
   Address:{
       type :String,
   },
   Gender:{
       type:String,
   },
   PhoneNumber:{
       type:Number,
       ref:'Account'
   },
   AccountID:{
        type: Schema.Types.ObjectId,
        ref: 'Account'
   },
   UserName:{
       type:String,
       ref:'Account'
   }
},{collection:'User',
   versionKey: false //here
});

버전 키입니다.새로운 갱신이 이루어질 때마다 갱신됩니다.개인적으로는 무효로 하고 싶지 않습니다.

[1]에 대한 자세한 내용은 다음 솔루션을 참조하십시오.Mongoose 버전 관리: 언제 비활성화해도 안전합니까?

'문서'의 '_v' 필드는 'optimic Concurrency' 우려 사항을 충족합니다.

이 용어는 기본적으로 mongoose에서 "findOne, findById"로 문서를 취득했지만 아직 mongoose의 save() 메서드를 사용하지 않았다는 것을 의미합니다.이 간격 동안 다른 코드가 동일한 문서를 취득하여 첫 번째 문서 인스턴스 앞에 .save() 메서드를 사용했을 경우 어떻게 됩니까?이 사용 사례에서, 만약 우리가 (mongoose specific) 버전 오류 같은 것을 던지고 싶다면, 우리는 사용합니다.optimisticConcurrency: true옵션을 지정합니다.

그런 다음 mongoose는 '_v1'을 사용하여 이 두 문서를 비교합니다.

없이optimisticConcurrency: true.__v'는 몽구스 1입니다.

주의: 'findOneAndUpdate' 종류의 조작에서는 '_v'는 갱신되지 않습니다.(save() updates만)

__v필드는 버전 키라고 불립니다.문서의 내부 리비전을 설명합니다.이 것 이쁘다.__v문서 수정 내용을 추적하기 위해 사용됩니다.필드는 문서의 수정사항을 추적하는 데 사용됩니다.기본적으로 값은 0 μm(트로값는 by default(, zero) 0 μm이다.__v:0를 참조해 주세요.

If you don't want to use this version key you can use the 이 버전 키를 사용하지 않으려면versionKey: false as ~하듯이mongoose.Schema매개 변수파라미터를 지정합니다.

이 예에 따를 수 있습니다.

const mongoose = require('mongoose');

const userSchema = mongoose.Schema(
    {
        name: {
            type: String,
            require: true
        },
        email: {
            type: String,
            unique: true
        },

        password: {
            type: String,
        }
    },
    {
        timestamps: true,
        versionKey: false, // Here You have to add.
    }
)

module.exports = mongoose.model('tbl_user', userSchema)

스키마 정의에서 versionKey: false를 사용할 수 있습니다.

'use strict';

const mongoose = require('mongoose');

export class Account extends mongoose.Schema {

    constructor(manager) {

        var trans = {
            tran_date: Date,
            particulars: String,
            debit: Number,
            credit: Number,
            balance: Number
        }

        super({
            account_number: Number,
            account_name: String,
            ifsc_code: String,
            password: String,
            currency: String,
            balance: Number,
            beneficiaries: Array,
            transaction: [trans]
        }, {
            versionKey: false // set to false then it wont create in mongodb
        });

        this.pre('remove', function(next) {
            manager
                .getModel(BENEFICIARY_MODEL)
                .remove({
                    _id: {
                        $in: this.beneficiaries
                    }
                })
                .exec();
            next();
        });
    }

}

언급URL : https://stackoverflow.com/questions/12495891/what-is-the-v-field-in-mongoose

반응형