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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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);
  }
  ...

Solution 2

Yes, I agree with the above answer. But here I would like to add some more important points to it. Looking at the Mongoose documentation, I feel like it should always be called with the new keyword since Schema is a constructor.

Both will work and are valid, but my suggestion is to only use the new mongoose.Schema() since it’s the correct way. Following standard conventions will make your code easier to read; not only for others but for you as well when you go back to it in 6 months.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply