A bit hazy on what imports can make available

I’m writing out a mongoose schema and realizing there’s a gap in my knowledge regarding what exactly is imported when you require a library. Here’s the code

const UserSchema = new mongoose.Schema({
    username : {
        type: String,

    }
});

My questions

  1. Is there any way to tell from the above code whether mongoose.Schema is a class or a constructor? I assume it’s a class but my constructor knowledge is hazy.

  2. Normally I would expect to set ‘type’ to ‘String’ (with quotes) but here there are none in the above code. Does that mean that there is a variable called “String” in Schema?

  3. Assuming #2 is yes, can we also infer that the class has some kind of logic to act on any argument that has an object key that has a string type and the string type is set to the ‘String’ variable? (Sorry for the long sentence but I’m trying to follow the reasoning precisely)

  1. A class is just a blueprint for an object, a description of what you want an object to look like. You create a new class by doing new myClass, ie you execute the function (the “constructor”) that creates the object. The question doesn’t quite make sense with this in mind - mongoose.Schema is a class, but it doesn’t do anything, new mongoose.Schema is the constructor being called to create an object of that class.
  2. It’s a domain specific language: somewhere within the codebase will be defined String and Boolean and whatever else to just make it simpler to type out things. type: String rather than having to take every string you want to save and write logic to check it’s a string.
  3. Yes, there will be some logic in the Mongoose codebase to check that whatever value you put in for those entries will be a string
1 Like

Ok, got it. The class is created by the constructor function using the new keyword. Constructor functions were a weak spot for me for a while so this helps get the concept better, thanks.

1 Like