Default function not working as expected

55 views
Skip to first unread message

TheBlinkstyKrab

unread,
Nov 14, 2019, 7:44:35 PM11/14/19
to Mongoose Node.JS ODM
Hi, I am running into a bit of an issue when using the default function. I'm not sure exactly how to explain this, so I'll try my best. 
Code:

const mongoose = require("mongoose");
const Flake = require("flakeid");

const flake = new Flake();

const UserSchema = mongoose.Schema({
    _id: {
        type: String,
        default: flake.gen()
    }
});

module.exports = mongoose.model("users"UserSchema);

The first time I create a document and save it, it works without errors. Any attempt after the first will result in a duplicate key error (this will reset after I restart my code).  It almost seems as if the data beign returned by the function is being "cached", and when the function is called a second time it just inserts the "cached" value in. 

Rob Ludwig

unread,
Nov 15, 2019, 2:58:34 PM11/15/19
to Mongoose Node.JS ODM
You are making the common mistake of confusing a function and the value of the function. In `default` you need to put the function that will be called every time a new user is created. That would be `flake.gen` (no parens) or maybe you would need `flake.gen.bind(flake)` depending on bindings. In either case that would be a function. 

Here you have put `flake.gen()`, which is not a function but the output of a function.
Reply all
Reply to author
Forward
0 new messages