Grateful Grateful - 2 months ago 7
Node.js Question

Creating Mongoose Schemas with or without 'new' keyword?

Most of the examples I have seen online do something like...

var UserSchema = new mongoose.Schema({
name: String,
age: String
});


However, recently I found a book do the above... but without the new keyword.

var UserSchema = mongoose.Schema({
name: String,
age: String
});


I am now confused. Do we use the new keyword for creating the schema or not.. and what happens in both cases?

Answer

Both are valid and returns a new instance of the Mongoose.Schema class. What this means is that both does exactly the same. This line checks whether you already have an instance of the Schema class, if not, it returns one for you.

To summarize, if you call

var schema = new mongoose.Schema({})

you initialize an instance yourself, while if you call

var schema = mongoose.Schema({})

mongoose initializes one for you, with this:

function Schema(obj, options) {
  if (!(this instanceof Schema)) {
    return new Schema(obj, options);
  }
  ...
Comments