4

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"?

Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48
Kevin
  • 1,147
  • 11
  • 21

2 Answers2

9

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);
danmactough
  • 5,444
  • 2
  • 21
  • 22
  • 1
    I got it. Thanks a lot. And I think design in this way could also make the schema reusable when there has different collections with the same schema. – Kevin Apr 12 '12 at 07:55
4

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.

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • If you did that: `var ArticleSchema = require("./ArticleSchema"); var Article1 = mongoose.Model("Article1", ArticleSchema); var Article2 = mongoose.Model("Article2", ArticleSchema);` How would you import/require those collections in another file?``` – morgs32 Jun 11 '14 at 20:32