mongoose.js中的架构和子文档 [英] Schema and subdocs in mongoose.js

查看:76
本文介绍了mongoose.js中的架构和子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习如何使用猫鼬,并试图设计可靠可变的模式.该应用程序将发布到不同的服务(例如Twitter,Tumblr)并将它们存储在一个集合中(发布").会有一些共性(例如,何时发布或简短摘要),但其他字段(如帖子内容,博客帖子的随附脚本)会有所不同.

Learning how to use mongoose, and am trying to design reliably-variable schemas. The app would post to different services (e.g. Twitter, Tumblr) and store them in one collection ("Posts"). There would be some commonalities (e.g. when it was published, or a short summary) but other fields (like post contents, a blog posts's accompanying scripts) would vary.

什么是解决此问题的好方法?有没有一种很好的方法将不同的集合绑定在一起,从而避免这种情况呢?参考文献/亚方案?使用Schema.Types.Mixed,并通过使用安全检查扩展默认方法来增强一致性?

What's a good way to approach this? Is there a good way to bind together different collections to avoid this in the first place? References/subschemas? Use Schema.Types.Mixed, and reinforce consistency by extending the default methods with safety checks?

// 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
});

推荐答案

也许 discriminators 对于您的情况可能是更好的选择.

Maybe the discriminators could be better option for your case.

鉴别器是一种模式继承机制.它们使您可以在同一个基础MongoDB集合的顶部拥有具有重叠模式的多个模型.

Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.

示例代码如下

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 );

这篇关于mongoose.js中的架构和子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆