为什么以这种方式设计猫鼬?

Kev*_*vin 4 model mongoose mongodb node.js odm

我是mongoose的新手,
如果我想定义一个模型,我可以使用以下内容:

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

但为什么不像这样编码:

var ArticleModel = new Model({ 
    // properties
});
Run Code Online (Sandbox Code Playgroud)

为什么以这种方式设计猫鼬?有什么情况可以重复使用"ArticleSchema"吗?

dan*_*ugh 9

它是这样设计的,因此您可以为子文档定义一个模式,该模式不会映射到不同的模型.请记住,集合和模型之间存在一对一的关系.

来自Mongoose网站:

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);
Run Code Online (Sandbox Code Playgroud)