我正在使用版本为3的Mongoose和版本为2.2的MongoDB。我注意到我的MongoDB文档中开始出现一个名为
__v
的字段。这与版本控制有关吗?它的用途是什么?从这里得知:
versionKey
是由Mongoose在创建文档时设置的属性。它的值包含了文档的内部版本信息。此文档属性的名称是可配置的,默认值为__v
。如果该名称与您的应用程序冲突,则可以进行如下配置:
new Schema({..}, { versionKey: '_somethingElse' })
__v === 0
)是安全的吗? - Explosion Pillsquery.select('-__v')
的意思是查询时不包含 "__v" 这个字段。@ExplosionPills 你需要添加 Mongoose 中间件,比如 schema.pre('save', function(next) { this.increment(); next(); })
。这段代码的作用是在保存数据前自增一个计数器。 - wprl好的,我看不到Tony的解决方案...所以我必须自己处理...
如果你不需要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通过将文档与versionKey相关联来解决此问题,在mongoose内部使用它确保它访问正确的集合版本。更多信息请参见:http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.htmlresultFromMongo.toObject({ versionKey: false })
,ن»¥وٹ‘هˆ¶è¯¥ه€¼م€‚ - Leo Gerberschema.set('versionKey', false);
- Stan Wiechers在 NestJS 中删除需要向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
});
optimisticConcurrency: true
选项。然后mongoose将使用'__v1'来比较这两个文档。如果没有optimisticConcurrency: true
选项,'__v'将没有效果,并且mongoose不会将其增加1。注意:在'findOneAndUpdate'等操作中,不会更新'__v'。(只有save()会更新)。这是版本密钥。每当进行新的更新时,它都会得到更新。我个人不喜欢将其禁用。
如果您想了解更多信息,请阅读以下解决方案: [1]: Mongoose版本控制:什么时候可以安全地禁用它?
__v
字段被称为版本键。它描述了文档的内部修订版本。这个__v
字段用于跟踪文档的修订。默认情况下,它的值为零(__v:0
)。
如果您不想使用这个版本键,您可以将versionKey:false
作为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)
{
_id: 1,
name: 'John',
age: 37,
__v: 0
}
After updating:
{
_id: 1,
name: 'John',
age: 40,
__v: 1
}
'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();
});
}
}