在mongoose的inheritance
你好,我需要在mongoose库inheritance我的模式。 有完整的插件吗? 或者我应该怎么做呢?
我还需要从Base模式inheritance所有的pre,post,init中间件。
你可能想看看使用Mongoose插件:
一个插件可以实现你想要的“开箱即用”function:
对于其他寻找这个function的人来说,Mongoose 3.8现在通过Discriminatorfunction具有了模式inheritance:
我知道这是一位老人,但是我到了这里寻找同一个问题的答案,最后做了一些与众不同的事情。 我不想使用鉴别器,因为所有文档都存储在同一个集合中。
ModelBase.js
var db = require('mongoose'); module.exports = function(paths) { var schema = new db.Schema({ field1: { type: String, required: false, index: false }, field2: { type: String, required: false, index: false } }, { timestamps: { createdAt: 'CreatedOn', updatedAt: 'ModifiedOn' } }); schema.add(paths); return schema; };
NewModel.js
var db = require('mongoose'); var base = require('./ModelBase'); var schema = new base({ field3: { type: String, required: false, index: false }, field4: { type: String, required: false, index: false } }); db.model('NewModelItem', schema, 'NewModelItems');
所有4个字段将在NewModelItem中。 使用ModelBase的其他模型,你想使用相同的领域/选项/等。 在我的项目中,我把时间戳放在那里。
在Schema构造函数中调用Schema.add,所以模型应该像所有的字段都是在原来的构造函数调用中发送一样进行组装。
如果你想使用不同的集合 :
function extendSchema (Schema, definition, options) { return new mongoose.Schema( Object.assign({}, Schema.obj, definition), options ); }
用法:
const UserSchema = new mongoose.Schema({ firstname: {type: String}, lastname: {type: String} }); const ClientSchema = extendSchema(UserSchema, { phone: {type: String, required: true} });
检查这个框架的模型为Mongoose:
https://github.com/marian2js/rode#models-with-mongoose
这是谁来扩展这个框架的例子:
首先在一个新的“模型”中定义你的模式:
var rode = require('rode'); var User = rode.Model.extend({ name: 'User', schema: { name: { type: 'String', unique: true }, email: String, password: String } });
现在你应该调用extend方法:
var Admin = User.extend({ name: 'Admin', // The schema for admins is the schema for users + their own schema schema: { lastAccess: Date } });
但是请注意,这个注释是从框架github中提取出来的:“这两个模型将在MongoDB上共享相同的集合,扩展模型的文档将有一个属性_type来区分。