Mehdi Yeganeh Mehdi Yeganeh - 4 months ago 19x
Node.js Question

How can i have auto-increment field in nedb?

I want to have exactly auto-increment field like relational or objective databases, so i need an integer

field with automatically set field value, value should be one more last record
value like this:



remove last record:


add new record:


I added a function to my datastore and calculate maximum of _id and plus 1
and set as field value, but there is problem here:

When we use auto-increment field in relational databases, it works like i said and after you
remove last record
it reserved a deleted record number and new inserted records continue increment but in my way its says the _id of removed record for new record.

My code is:

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;

data["_id"] = newIndex;

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


You can store the last value of the index in the database. Something like that

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

// Initialize the initial index value
// (if it already exists in the database, it is not overwritten)
db.insert({_id: '__autoid__', value: -1});

db.getAutoId = function(onFind) {
  db.findOne( { _id: '__autoid__' }, function(err, doc) {
    if (err) {
      onFind && onFind(err)
    } else {
      // Update and returns the index value
      db.update({ _id: '__autoid__'}, { $set: {value: ++doc.value} }, {},
         function(err, count) {
           onFind && onFind(err, docValue);
  return db;