gpt4 book ai didi

node.js - nedb 中如何拥有自动增量字段?

转载 作者:行者123 更新时间:2023-12-02 21:16:01 29 4
gpt4 key购买 nike

我想要像关系数据库或目标数据库一样具有精确的自动增量字段,因此我需要一个具有自动设置字段值的整数_id字段,值应该是最后一个记录_id 值如下:

数据:

{_id:1,name"foo"}
{_id:2,name"bar"}

删除最后一条记录:

{_id:1,name"foo"}

添加新记录:

{_id:1,name"foo"}
{_id:3,name"newbar"}

我向数据存储区添加了一个函数,计算 _id 的最大值并加 1 max(_id)+1 并设置为字段值,但这里有问题:

当我们在关系数据库中使用自动增量字段时,它的工作原理就像我说的那样,在您删除最后一条记录之后,它保留了已删除的记录号,并且新插入的记录继续增量,但以我的方式它说新记录的删除记录的_id。

我的代码是:

var Datastore = require('nedb'),
localDb = new Datastore({
filename: __dirname + '/dbFilePath.db',
autoload: true
});

localDb.getMax = function(fieldName, onFind){
db.find({}).sort({_id:-1}).limit(1).exec(function (err, docs) {onFind && onFind(err, docs['_id']);});
return localDb;
}

localDb.insertAutoId = function(data, onAdd){
var newIndex = 0;
localDb.getMax(function (err, maxValue) {
newIndex = maxValue+1;

if(!data["_id"])
data["_id"] = newIndex;

localDb.insert(data, function (err, newDoc) {
onAdd && onAdd(err, newDoc);
});
});
return localDb;
}

最佳答案

nedb 的改进答案是:

db.getAutoincrementId = function (cb) {
this.update(
{ _id: '__autoid__' },
{ $inc: { seq: 1 } },
{ upsert: true, returnUpdatedDocs: true },
function (err, affected, autoid) {
cb && cb(err, autoid.seq);
}
);
return this;
};

这相当于mongodb方式:

db.getAutoincrementId = function (cb) {
this.findAndModify({
query: { _id: '__autoid__' },
update: { $inc: { seq: 1 } },
new: true
}
function (err, autoid) {
cb && cb(err, autoid.seq);
}
);
return this;
};

关于node.js - nedb 中如何拥有自动增量字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37508113/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com