How can i have auto-increment field in nedb?
<p>I want to have exactly auto-increment field like relational or objective databases, so i need an integer <code>_id</code> field with automatically set field value, value should be one more last record <code>_id</code> value like this:</p>

<p>data:</p>

<pre><code>{_id:1,name"foo"}
{_id:2,name"bar"}
</code></pre>

<p>remove last record:</p>

<pre><code>{_id:1,name"foo"}
</code></pre>

<p>add new record:</p>

<pre><code>{_id:1,name"foo"}
{_id:3,name"newbar"}
</code></pre>

<p>I added a function to my datastore and calculate maximum of _id and plus 1 <code>max(_id)+1</code> and set as field value, but there is problem here:</p>

<p>When we use auto-increment field in relational databases, it works like i said and after you <code>remove last record</code> 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.</p>

<p>My code is:</p>

<pre><code>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 &amp;&amp; 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 &amp;&amp; onAdd(err, newDoc);
        });
    });
    return localDb;
}
</code></pre>