Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 440
Grateful Avatar asked Sep 27 '16 08:09

Grateful


People also ask

Is schema necessary for Mongoose?

Mongoose Schematype is a configuration for the Mongoose model. Before creating a model, we always need to create a Schema. The SchemaType specifies what type of object is required at the given path. If the object doesn't match, it throws an error.

Can we create Mongoose model without schema?

You can use Mongoose with the collections that have schema and the node driver or another mongo module for those schemaless ones.

What is difference between create and save in Mongoose?

1 Answer. The . save() is considered to be an instance method of the model, while the . create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.

Which are the valid schema types useful while defining a schema in Mongoose?

You can also define MongoDB indexes using schema type options. index : boolean, whether to define an index on this property. unique : boolean, whether to define a unique index on this property. sparse : boolean, whether to define a sparse index on this property.


1 Answers

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);
  }
  ...
like image 115
Svenskunganka Avatar answered Sep 21 '22 01:09

Svenskunganka