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"?
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);
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.