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?
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.
You can use Mongoose with the collections that have schema and the node driver or another mongo module for those schemaless ones.
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.
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.
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);
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With