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

2 Answers 2

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);
1
  • 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, 2012 at 7: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.

1
  • 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, 2014 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.