学习如何使用猫鼬,并尝试设计可靠可变的模式。该应用程序将发布到不同的服务(例如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
});
最佳答案
也许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 );
关于node.js - mongoose.js中的架构和子文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35615633/