在mongoose.js中的模式和子目录

学习如何使用mongoose,并试图devise可靠的variables模式。 该应用程序将张贴到不同的服务(如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可能是更好的select你的情况。

鉴别器是一个模式inheritance机制。 它们使您能够在相同的基础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 );