【问题标题】:Schema and subdocs in mongoose.jsmongoose.js 中的架构和子文档
【发布时间】:2016-06-07 12:55:36
【问题描述】:

正在学习如何使用 mongoose,并且正在尝试设计可靠可变的架构。该应用程序将发布到不同的服务(例如 Twitter、Tumblr)并将它们存储在一个集合中(“帖子”)。会有一些共同点(例如发布时间或简短摘要),但其他领域(例如帖子内容、博客帖子的随附脚本)会有所不同。

有什么好的方法来解决这个问题?有没有一种好方法可以将不同的集合绑定在一起来避免这种情况?参考/子模式?使用Schema.Types.Mixed,并通过使用安全检查扩展默认方法来加强一致性?

// Example pseudo-functioning schemas
const tweetSchema = new mongoose.Schema({
  tweetUrl: {type: string, trim: true}
  length: Number
});

const blogSchema = new mongoose.Schema({
  title: String,
  edits: [Date],
  slug: { type: String, trim: true},
  body: String
});

const postSchema = new mongoose.Schema({
  published: Date,
  summary: String,
  type: String,
  contents: blogSchema || tweetSchema
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    也许discriminators 可能是您的更好选择。

    鉴别器是一种模式继承机制。它们使您能够在同一个基础 MongoDB 集合之上拥有多个具有重叠模式的模型。

    示例代码如下

    var options = {discriminatorKey: 'contents'};
    const postSchema = new mongoose.Schema({
      published: Date,
      summary: String,
      type: String,
    }, options);
    var Post = mongoose.model('Post', postSchema);
    
    const tweetSchema = new mongoose.Schema({
      tweetUrl: {type: string, trim: true}
      length: Number
    }, options);
    var Tweet = Post.discriminator('Tweet', tweetSchema);
    
    const blogSchema = new mongoose.Schema({
      title: String,
      edits: [Date],
      slug: { type: String, trim: true},
      body: String
    }, options);
    var Blog = Post.discriminator('Blog', blogSchema );
    

    【讨论】:

    • 这看起来很像我要找的东西——谢谢!
    猜你喜欢
    • 2014-07-10
    • 2015-03-26
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多