Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Doesn't generate unique strings in a Mongoose schema #1

Closed
shanev opened this Issue · 3 comments

3 participants

@shanev

I'm using shortid to generate a unique id for a Mongoose schema, like so:


Photo = new mongoose.Schema({
  _id: {
    type: String,
    default: shortId.generate()
  }
});

However, when subsequent Photos are created, the generated id is always the same. Not sure if this a Mongoose issue or shortid issue.

@dylang
Owner

Hi, thanks for giving shortId a try.

I think your'e using mongoose.Schema incorrectly. shortId.generate() returns a string (not a function) - so the way you have it in your code it only runs once - therefore the value will always be the same. You need mongoose to run shortId.generate every time it needs a new id.

I haven't used mongoose yet. Is something like this possible?


Photo = new mongoose.Schema({
  _id: {
    type: String,
    default: function() { return shortId.generate(); }
  }
});
@shanev

Mongoose defaults either take a function or value. So all I had to do was get rid of the (). Works like a charm now. Thanks!

@shanev shanev closed this
@danilodeveloper

it worked for me:

    publicId: {
        type: String,
        unique: true,
        'default': shortid.generate
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.