mongodb error getNextSequence is not defined

2

Good morning, I can not create and execute this function in mondodb 3.4 I'm following this tutorial: Create an Auto-Incrementing Sequence Field

Error Error: ReferenceError: getNextSequence is not defined: @ (shell): 3: 6

function getNextSequence(name) {
var ret = db.counters.findAndModify(
      {
        query: { _id: name },
        update: { $inc: { seq: 1 } },
        new: true
      }
  );
return ret.seq;
 }

When I run this command on mongodb This is giving error.

db.users.insert(
{
 _id: getNextSequence("userid"),
 name: "Sarah C."
}
)

Failed to execute script.

Error: ReferenceError: getNextSequence is not defined: @ (shell): 3: 6

    
asked by anonymous 23.05.2017 / 19:19

2 answers

2

You need to save the function before and then load it, as suggested by @Gigano:

db.system.js.save(
   {
     _id: "getNextSequence",
     value : function (name) { return x; }
   }
)

And then:

db.loadServerScripts();
    
23.05.2017 / 19:41
1

Try to force load MongoDB shell functions using:

> db.loadServerScripts();

See more here .

    
23.05.2017 / 19:34