mongodb getNextSequence error is not defined

Asked

Viewed 189 times

2

Good morning, I am unable to 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 You’re making a mistake.

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

Failed to execute script.

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

2 answers

2

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

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

And then:

db.loadServerScripts();

1

Try to force loading of Mongodb shell functions using:

> db.loadServerScripts();

See more here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.