Meteor Methods in autoValue || defaultValue of Simple-Schema

Hey all,

I have looked everywhere on stackoverflow without any leads so I’m hoping someone can help here.

I’m trying to implement an auto-increment field in a Simple-Schema with autoValue or defaultValue.
Within the function I am making a Meteor.call to a method I have defined on the server.

Here’s my stuff:
lib/collections/simple-schemas.js

if (Meteor.isServer) {
    Schemas = {};

    Schemas.Guests = new SimpleSchema({
        guest_id: {
            type: Number,
            label: "guest_id",
            min: 0,
            autoValue: function() {
                if (this.isInsert && Meteor.isServer) {
                    return Meteor.call("getNextSequence", "guest_id");
                }
                // ELSE omitted intentionally
            }
        },
        firstName: {
            type: String,
            label: "First Name",
            max: 200
        },
        lastName: {
            type: String,
            label: "Last Name",
            max: 200
        }
    });

    Guests.attachSchema(Schemas.Guests);
}

and my methods are defined here:
lib/methods.js

if (Meteor.isServer) {
Meteor.startup(function() {

Meteor.methods({

    getNextSequence: function(counter_name) {

        console.log("Counter: " + counter_name);

        if (Counters.findOne({
                _id: counter_name
            }) == 0) {

            Counters.insert({
                _id: counter_name,
                seq: 0
            });

            console.log("Initialized counter: " + counter_name + " with a sequence value of 0.");
            return 0;

        } else {

            counter = Counters.findOne({
                _id: counter_name
            });
            console.log("Counter " + counter_name + ": " + counter.seq);

            Counters.update({
                _id: counter_name
            }, {
                $inc: {
                    seq: 1
                }
            });

            return counter.seq;
        }
    }

});

});
}

I’m getting a Method not found [404] error though. Any thoughts on how to get around this? Or does anyone have a better implementation of an auto-increment field?

Cheers,

Maggie

Take care the order Meteor loads files.

Sorry, it’s not the matter of order.
I think your methods should not be defined wrapped by Meteor.startup.

And by the way, where is your Guests.insert called?
I did a test here. No error occured.

I see you have ensured this happens on the server (which is good), but the solution you have outlined has a design flaw - it is possible for two or more concurrent requests for a new autoincrement value to get the same result due to race conditions.

This may help: Automatically increment order numbers

Thanks for the tip. Since yesterday I tried the Future package, but it still wasn’t working. I will try your solution.