Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was mongoose designed in this way?

I'm new to mongoose,
If I want to define a model, I could use the following:

var ArticleSchema = new Schema({
    _id: ObjectId,
    title: String,
    content: String,
    time: { type: Date, default: Date.now }
});
var ArticleModel = mongoose.model("Article", ArticleSchema);

But why not just code like this:

var ArticleModel = new Model({ 
    // properties
});

Why was mongoose designed in this way? Is there any situation where I can reuse "ArticleSchema"?

like image 924
Kevin Avatar asked Dec 13 '22 03:12

Kevin


2 Answers

It's designed that way so that you can define a schema for subdocuments, which do not map to distinct models. Keep in mind that a there is a one-to-one relation between collections and models.

From the Mongoose website:

var Comments = new Schema({
    title     : String
  , body      : String
  , date      : Date
});

var BlogPost = new Schema({
    author    : ObjectId
  , title     : String
  , body      : String
  , buf       : Buffer
  , date      : Date
  , comments  : [Comments]
  , meta      : {
      votes : Number
    , favs  : Number
  }
});

var Post = mongoose.model('BlogPost', BlogPost);
like image 177
danmactough Avatar answered Dec 14 '22 16:12

danmactough


Yeah sometimes I split the Schema's up into separate files and do this kind of thing.

// db.js 
var ArticleSchema = require("./ArticleSchema");
mongoose.Model("Article", ArticleSchema);

It's only really useful when you have a bunch of static and other methods on models and the main model file gets messy.

like image 27
Jamund Ferguson Avatar answered Dec 14 '22 17:12

Jamund Ferguson