在mongoDB文档的以下链接中:https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
关于如何使用自动增量_id构建“安全”插入,有一个解释。我的问题是:
如果函数存储为JS函数是JS文件,我无法退出。还是存储在数据库中?或者别的什么。
谢谢。
下面是在上面的链接中引入的实际功能:
function insertDocument(doc, targetCollection) {
while (1) {
var cursor = targetCollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);
var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;
doc._id = seq;
var results = targetCollection.insert(doc);
if( results.hasWriteError() ) {
if( results.writeError.code == 11000 /* dup key */ )
continue;
else
print( "unexpected error inserting data: " + tojson( results ) );
}
break;
}
}发布于 2015-11-12 09:19:52
实施方法
下面是一个示例,说明如何使用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();
});
});来源:https://stackoverflow.com/a/30164636/236660
请注意,对于使用此代码的每个集合,应该设置不同的{_id: 'entityId'}。因此,如果您要为entitySchema生成一个ID,那么您将拥有{_id: 'entityId'}。对于userSchema,您将使用{_id: 'userId'}等。您需要这样做,以便每个集合都有自己的自动递增序列。
上面的代码是线程安全的。findByIdAndUpdate操作是原子操作;其一致性和并发性由MongoDB处理。
现有模块
另外,还有一个专门为处理自动递增is而创建的mongoose模块.实际上,您最好使用它:
https://stackoverflow.com/questions/33649445
复制相似问题