xcode
xcode

Reputation: 1717

Create schema on mongoose whether to use 'new' keyword or not?

I understand what is the use of Schema and model in mongoose, however when defining/creating a new Schema there are 2 ways of doing it (that I found of), and I'm confused by it,

1st way (without new - no instance created):

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbName');

// No 'new' keyword
var mySchema = mongoose.Schema({
    parameter1 : String,
    parameter2 : String
});

var modelName = mongoose.model('collectionName', mySchema);

and 2nd way of doing it (with new - an instance created):

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbName');

// There is 'new' keyword
var mySchema = new mongoose.Schema({
    parameter1 : String,
    parameter2 : String
});

var modelName = mongoose.model('collectionName', mySchema);

What's the differences between the two? when to use one or the other?

Upvotes: 2

Views: 803

Answers (1)

Both way are fine, but according to code standard and mongoose library, we use 2nd way. It's follow extending & Implementation feature like OOP.

Schema & Model we use in nodejs for validation & restrict unwanted object & fields inserting into mongo collection.

Thats the reason for uses.

Upvotes: 2

Related Questions