-1

I am trying to get by code the next sequence number but it always says "undefined".

I did this in my mongoDB before:

db.PresentationCollection.insert(
   {
      _id: "editorID",
      seq: 0
   }
)

my code (name is editorID):

function getNextSequence(name, db) {

    var collection = db.get('PresentationCollection');

    var ret = collection.findAndModify(
           {
               query: { _id: name },
               update: { $inc: { seq: 1 } },
               new: true
           }
    );

    return ret.seq;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
spinker
  • 298
  • 4
  • 20

2 Answers2

0

You're missing the callback. Callback-based asynchronous functions generally do not return anything meaningful. See the documentation for findAndModify in the node binding's readme.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • not working for me, i think i mistake with the syntax, can you write here something that works ? – spinker Apr 29 '14 at 19:37
0

I had the same problem from following this link and it is indeed the callback not being specified and your code not waiting for the returned result - mongo db documents create auto increment

Here is what I did to solve it. Keep in mind I am using Q for promise helping but you could use straight up javascript promises.

function _getNextSequence(name) {
  var deferred = Q.defer();
  db.counters.findAndModify(
    { _id: name }, //query
    [], //sort
    { $inc: { seq: 1 } }, //update
    { new:true }, //options
    function(err, doc) { //callback
      if (err) deferred.reject(err.name + ': ' + err.message);
      if (doc){
        deferred.resolve(doc.value.seq);
      }
  });
  return deferred.promise;
}
spartikus
  • 2,852
  • 4
  • 33
  • 38