[英]Mongoose auto increment
根据这篇 mongodb 文章,可以自动增加一个字段,我想使用计数器收集方式。
该示例的问题在于,我没有成千上万的人使用 mongo 控制台在数据库中输入数据。 相反,我正在尝试使用猫鼬。
所以我的架构看起来像这样:
var entitySchema = mongoose.Schema({
testvalue:{type:String,default:function getNextSequence() {
console.log('what is this:',mongoose);//this is mongoose
var ret = db.counters.findAndModify({
query: { _id:'entityId' },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
}
});
我在同一个数据库中创建了计数器集合,并添加了一个 _id 为“entityId”的页面。 从这里我不确定如何使用猫鼬来更新该页面并获取递增的数字。
计数器没有架构,我希望它保持这种状态,因为这并不是应用程序真正使用的实体。 它只能在模式中使用以自动增加字段。
以下是如何在 Mongoose 中实现自动递增字段的示例:
var CounterSchema = Schema({
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);
var entitySchema = mongoose.Schema({
testvalue: {type: String}
});
entitySchema.pre('save', function(next) {
var doc = this;
counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter) {
if(error)
return next(error);
doc.testvalue = counter.seq;
next();
});
});
您可以使用mongoose-auto-increment
包,如下所示:
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
/* connect to your database here */
/* define your CounterSchema here */
autoIncrement.initialize(mongoose.connection);
CounterSchema.plugin(autoIncrement.plugin, 'Counter');
var Counter = mongoose.model('Counter', CounterSchema);
您只需要初始化autoIncrement
一次。
投票最多的答案不起作用。 这是修复:
var CounterSchema = new mongoose.Schema({
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);
var entitySchema = mongoose.Schema({
sort: {type: String}
});
entitySchema.pre('save', function(next) {
var doc = this;
counter.findByIdAndUpdateAsync({_id: 'entityId'}, {$inc: { seq: 1} }, {new: true, upsert: true}).then(function(count) {
console.log("...count: "+JSON.stringify(count));
doc.sort = count.seq;
next();
})
.catch(function(error) {
console.error("counter error-> : "+error);
throw error;
});
});
options参数为您提供更新的结果,如果它不存在,它会创建一个新文档。 你可以在这里查看官方文档。
如果您需要排序索引,请查看此文档
所以结合多个答案,这就是我最终使用的:
counterModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const counterSchema = new Schema(
{
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
}
);
counterSchema.index({ _id: 1, seq: 1 }, { unique: true })
const counterModel = mongoose.model('counter', counterSchema);
const autoIncrementModelID = function (modelName, doc, next) {
counterModel.findByIdAndUpdate( // ** Method call begins **
modelName, // The ID to find for in counters model
{ $inc: { seq: 1 } }, // The update
{ new: true, upsert: true }, // The options
function(error, counter) { // The callback
if(error) return next(error);
doc.id = counter.seq;
next();
}
); // ** Method call ends **
}
module.exports = autoIncrementModelID;
我的模型.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const autoIncrementModelID = require('./counterModel');
const myModel = new Schema({
id: { type: Number, unique: true, min: 1 },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date },
someOtherField: { type: String }
});
myModel.pre('save', function (next) {
if (!this.isNew) {
next();
return;
}
autoIncrementModelID('activities', this, next);
});
module.exports = mongoose.model('myModel', myModel);
注意力!
正如hammerbot和dan-dascalescu指出的那样,如果您删除文档,这将不起作用。
如果将3个文件ID为
1
,2
和3
-删除2
并插入另一新的一个,它会得到3
作为ID,其已被使用!
如果您永远不会删除文档,请执行以下操作:
我知道这已经有很多答案,但我会分享我的解决方案,它是 IMO 简短易懂的:
// Use pre middleware
entitySchema.pre('save', function (next) {
// Only increment when the document is new
if (this.isNew) {
entityModel.count().then(res => {
this._id = res; // Increment count
next();
});
} else {
next();
}
});
确保entitySchema._id
具有type:Number
。 猫鼬版本: 5.0.1
。
这个问题已经足够复杂并且有足够多的陷阱,因此最好依赖经过测试的猫鼬插件。
在http://plugins.mongoosejs.io/上的大量“自动增量”插件中,维护和记录得最好的(而不是分叉)是mongoose sequence 。
我结合了答案的所有(主观和客观)好的部分,并提出了以下代码:
const counterSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
seq: {
type: Number,
default: 0,
},
});
// Add a static "increment" method to the Model
// It will recieve the collection name for which to increment and return the counter value
counterSchema.static('increment', async function(counterName) {
const count = await this.findByIdAndUpdate(
counterName,
{$inc: {seq: 1}},
// new: return the new value
// upsert: create document if it doesn't exist
{new: true, upsert: true}
);
return count.seq;
});
const CounterModel = mongoose.model('Counter', counterSchema);
entitySchema.pre('save', async function() {
// Don't increment if this is NOT a newly created document
if(!this.isNew) return;
const testvalue = await CounterModel.increment('entity');
this.testvalue = testvalue;
});
这种方法的好处之一是所有与计数器相关的逻辑都是独立的。 您可以将其存储在单独的文件中,并将其用于导入CounterModel
多个模型。
如果要增加_id
字段,则应在架构中添加其定义:
const entitySchema = new mongoose.Schema({
_id: {
type: Number,
alias: 'id',
required: true,
},
<...>
});
我不想使用任何插件(一个额外的依赖,除了我在 server.js 中使用的那个之外初始化 mongodb 连接,等等......)所以我做了一个额外的模块,我可以在任何模式下使用它,并且甚至,我正在考虑何时从数据库中删除文档。
module.exports = async function(model, data, next) {
// Only applies to new documents, so updating with model.save() method won't update id
// We search for the biggest id into the documents (will search in the model, not whole db
// We limit the search to one result, in descendant order.
if(data.isNew) {
let total = await model.find().sort({id: -1}).limit(1);
data.id = total.length === 0 ? 1 : Number(total[0].id) + 1;
next();
};
};
以及如何使用它:
const autoincremental = require('../modules/auto-incremental');
Work.pre('save', function(next) {
autoincremental(model, this, next);
// Arguments:
// model: The model const here below
// this: The schema, the body of the document you wan to save
// next: next fn to continue
});
const model = mongoose.model('Work', Work);
module.exports = model;
希望对你有帮助。
(如果这是错误的,请告诉我。我对此没有任何问题,但是,不是专家)
test.pre("save",function(next){ if(this.isNew){ this.constructor.find({}).then((result) => { console.log(result) this.id = result.length + 1; next(); }); } })
即使文档已经有一个 _id 字段(排序,无论如何),答案似乎会增加序列。 如果您“保存”以更新现有文档,就会出现这种情况。 不?
如果我是对的,如果 this._id !== 0,你会想调用 next()
猫鼬文档对此并不十分清楚。 如果它在内部执行更新类型查询,则可能不会调用 pre('save'。
澄清
看来确实在更新时调用了“保存”预方法。
我认为您不想不必要地增加序列。 它会花费您一次查询并浪费序列号。
这是一个建议。
创建一个单独的集合来保存模型集合的最大值
const autoIncrementSchema = new Schema({
name: String,
seq: { type: Number, default: 0 }
});
const AutoIncrement = mongoose.model('AutoIncrement', autoIncrementSchema);
现在为每个需要的schema添加一个pre-save hook
。
例如,让集合名称为Test
schema.pre('save', function preSave(next) {
const doc = this;
if (doc.isNew) {
const nextSeq = AutoIncrement.findOneAndUpdate(
{ name: 'Test' },
{ $inc: { seq: 1 } },
{ new: true, upsert: true }
);
nextSeq
.then(nextValue => doc[autoIncrementableField] = nextValue)
.then(next);
}
else next();
}
由于findOneAndUpdate
是atomic
操作,因此没有两个更新会返回相同的seq
值。 因此,无论并发插入的数量如何,您的每个插入都将获得增量 seq。 这也可以扩展到更复杂的自动增量逻辑,并且自动增量序列不限于Number类型
这不是经过测试的代码。 使用前先测试,直到我为mongoose
制作插件。
更新我发现这个插件实现了相关的方法。
在通过 put() 为 Schema 的字段赋值时,我在使用 Mongoose Document 时遇到了问题。 count
返回一个对象本身,我必须访问它的属性。
我在@Tigran 的回答中玩过,这是我的输出:
// My goal is to auto increment the internalId field
export interface EntityDocument extends mongoose.Document {
internalId: number
}
entitySchema.pre<EntityDocument>('save', async function() {
if(!this.isNew) return;
const count = await counter.findByIdAndUpdate(
{_id: 'entityId'},
{$inc: {seq: 1}},
{new: true, upsert: true}
);
// Since count is returning an array
// I used get() to access its child
this.internalId = Number(count.get('seq'))
});
版本:猫鼬@5.11.10
当您的架构中有唯一字段时,上述答案均无效,因为数据库级别的唯一检查和增量发生在数据库级别验证之前,因此您可能会像上述解决方案一样跳过自动增量中的大量数字
我一起使用@cluny85 和@edtech。 但我没有完成完成这个问题。
counterModel.findByIdAndUpdate({_id: 'aid'}, {$inc: { seq: 1} }, function(error,counter){
但是在函数 "pre('save...) 然后更新计数器的响应在保存后完成文档。所以我不会将计数器更新为文档。
请再次检查所有答案。谢谢。
对不起。 我无法添加评论。 因为我是新手。
完美运行的解决方案
Mongodb AutoIncrement 字段
我创建了一个解决这个问题的项目
检查它https://github.com/HipsterSantos/mongo-lastIndex
你可以这样做
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
let counter = 1;
let CountedId = {type: Number, default: () => counter++};
const ModelSchema = new Schema({
id: CountedId,
// ....
});
const Model = Mongoose.model('Model', ModelSchema);
module.exports = Model;
Model.find({ id: { $gt: 0 } }).sort({ id: -1 })
.then(([first, ...others]) => {
if (first)
counter = first.id + 1;
});
var CounterSchema = Schema({
_id: { type: String, required: true },
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);
var entitySchema = mongoose.Schema({
testvalue: { type: String }
});
entitySchema.pre('save', function(next) {
if (this.isNew) {
var doc = this;
counter.findByIdAndUpdate({ _id: 'entityId' }, { $inc: { seq: 1 } }, { new: true, upsert: true })
.then(function(count) {
doc.testvalue = count.seq;
next();
})
.catch(function(error) {
throw error;
});
} else {
next();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.