Answer a question

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();
});

Answers

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.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐