MongoDB and Nodejs insert ID with auto increment

Related searches

I am new to NodeJs and MongoDB, i want to insert row with auto increment primary key 'id'. also defined a function called getNextSequence on mongo server.

this is working perfect on Mongodb server

 > db.user.insert({   
     "id" : getNextSequence('user_id'), 
     "username" : "test", 
     "email" : "test@test.com", 
     "password" : "test123" 
 })

now i want to insert from NodeJs.I have tried this but not working

db.collection('user').insertOne({
    id : "getNextSequence('user_id')",  
    username : query.name, 
    email: query.email, 
    password: query.pass
}, function(err, result) {
    assert.equal(err, null);
    console.log("row insterted ");
    callback();
});

Assuming that getNextSequence is a server-script function (i.e. a method you defined and saved via db.system.js.save), it is not callable outside of the server. One way to go is to use eval, which forces the server to evaluate a string as a js code, even though it is not a good practice. Here is an example:

db.eval('getNextSequence(\'user_id\')', function(err, result) {
  db.collection('users').insert({   
        "id" : result, 
        "username" : "test", 
        "email" : "test@test.com", 
        "password" : "test123" 
    });
});

Another way is to follow the mongo tutorial and to implement the getNextSequence directly in NodeJS. The syntax is pretty much the same:

function getNextSequence(db, name, callback) {
    db.collection("counters").findAndModify( { _id: name }, null, { $inc: { seq: 1 } }, function(err, result){
        if(err) callback(err, result);
        callback(err, result.value.seq);
    } );
}

You then use it in your nodeJS code like:

getNextSequence(db, "user_id", function(err, result){
    if(!err){
        db.collection('users').insert({
            "_id": result,
            // ...
        });
    }
});

Note: of course, you need to have set the counters collection as explained in the docs.

MongoDB and Nodejs insert ID with auto increment, I am new to NodeJs and MongoDB, i want to insert row with auto increment primary key 'id'. also defined a function called getNextSequence on mongo server. Tried to insert auto increment number for serial number in mongodb using mongoose and nodejs but not working.Where i want to update my code to find solution.If anyone knows please help to find solu

You can also use "mongodb-autoincrement" module of node js. For example:

var autoIncrement = require("mongodb-autoincrement");
exports.yourMethod = function(newData, callback) {
                    autoIncrement.getNextSequence(db, your-collection-name, function (err, autoIndex) {
                        newData.id = autoIndex;
                    //save your code with this autogenerated id
                });
}

Auto Increment Sequence in MongoDB, About 1 year ago I developed a nodejs REST API that was supposed to and it was generating old school integer primary keys for each inserted object. If you need auto incrementing id field in MongoDB — I recommend� Insert into the counters collection, the initial value for the userid: db.counters.insert( { _id: "userid", seq: 0 } ) Create a getNextSequence function that accepts a name of the sequence. The function uses the findAndModify() method to atomically increment the seq value and return this new value:

You can also use "mongoose-auto-increment".

The code has just 4 lines

  1. var mongoose = require('mongoose');
  2. var autoIncrement = require('mongoose-auto-increment');
  3. autoIncrement.initialize(mongoose.connection);
  4. userSchema.plugin(autoIncrement.plugin, 'user');

example :

npm i mongoose-auto-increment

connections.js :

const mongoose = require('mongoose');
require("dotenv").config;

const uri = process.env.MONGOURL;
mongoose.connect(uri, { useNewUrlParser: true }, (err) => {
    if (!err) { console.log('MongoDB Connection Succeeded.') }
    else { console.log('Error in DB connection : ' + err) }
});

require('../schema/userSchema');

userSchema.js :

var mongoose = require('mongoose');  // 1. require mongoose
var autoIncrement = require('mongoose-auto-increment'); // 2. require mongoose-auto-increment

var userSchema = new mongoose.Schema({
    name: { type: String  },  
    password: { type: String },  
    email: { type: String, unique: true, required: 'This field is required.' },    
});

autoIncrement.initialize(mongoose.connection); // 3. initialize autoIncrement 

userSchema.plugin(autoIncrement.plugin, 'user'); // 4. use autoIncrement
mongoose.model('user', userSchema);

MongoDB integer primary key (nodejs example) using server side , Let's use the following steps to generate the MongoDB auto increment sequence for the item id: Generate sample collection. Insert a document into a collection. Insert the record into a collection. Database sequence. Create a JavaScript function. Use JavaScript function. View inserted a record from store collection. How to create auto increment ID in mongoose (Node js) other than _id recently inserted auto-increment id from mysql a .csv file in node js; increment counter

Generate MongoDB Auto Increment Sequence - In 7 Steps, MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. However, there may be scenarios where we may want the _id field to have some auto-incremented value other than the ObjectId.

Normally MongoDB uses by default 12 bytes object id for the _id field as the primary key to uniquely identify the collection documents in MongoDB, for use of _id field there is a scenario to have some auto-increment value other than object _id in MongoDB.

Here, we can clearly observe that the item_id for these inserted records are 1, 2 and 3 as an auto incremented sequence of step 1 which is very similar to that of the traditional relational database sequence. Conclusion: – In this article, we discussed about the use of the auto increment sequence in the MongoDB along with a suitable example.

Comments
  • Why is getNextSequence('user_id') a string ?
  • when i am writing it as a function .. nodejs showing error , that it is not defined as a function.... because i have define this function on mongodb server
  • i dnot know how to pass it
  • Is your function set into db.system.js ?
  • it inserting NULL values?
  • I corrected the id of the sequence to match your code.
  • you mean result is null ?
  • I get an error. I am using same code suggested by you. TypeError: Cannot read property 'value' of null