继承猫鼬模式 [英] Inheriting Mongoose schemas
问题描述
我想创建一个基本的实体模式",其他模型实体将从其继承. 我做到了,但后来发生了奇怪的事情.
I wanted to make a base 'Entity Schema', and other model entities would inherit from it. I did it, kinda, but then strange thing happened.
这些是我的架构:
- AbstractEntitySchema
- MessageSchema
- UserSchema
- RoomSchema
文件: https://github.com/mihaelamj/nodechat/blob/master/models/db/mongo/schemas.js
但是在MongoDB中,它们都保存在同一文档存储中:实体模型"不是单独的模型,例如消息,用户. 我得到了应该发生的事情,但没有我想要的分开的商店吗? 如果是这样,我只是将一个基本的JSON/对象作为实体,并为每个实体附加适当的属性.或者,还有更好的方法? 谢谢.
But in MongoDB, they are all saved in the same document store: 'entity models' not separate ones, like Messages, Users.. Did I get what was supposed to happen, but not what I wanted, separate stores? If so I will just make a basic JSON/object as entity and append the appropriate properties for each entity. Or is there a better way? Thanks.
推荐答案
Discriminators
是模式继承机制.它们使您可以在相同的基本MongoDB集合之上具有重叠模式的多个模型.而不是其他文件.似乎您误解了猫鼬的discriminators
.这是一篇可以帮助您正确捕获它的文章.
Discriminators
are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection. rather than different documents. It seems that you misunderstand the discriminators
of mongoose. Here is one article could help you to catch it correctly.
这里有一些代码示例可以满足您的要求,将派生的架构另存为单独的文档
Here are some codes sample to meet your requirement, to save the derived schema as separated documents
function AbstractEntitySchema() {
//call super
Schema.apply(this, arguments);
//add
this.add({
entityName: {type: String, required: false},
timestamp: {type: Date, default: Date.now},
index: {type: Number, required: false},
objectID: {type: String},
id: {type: String}
});
};
util.inherits(AbstractEntitySchema, Schema);
//Message Schema
var MessageSchema = new AbstractEntitySchema();
MessageSchema.add({
text: {type: String, required: true},
author: {type: String, required: true},
type: {type: String, required: false}
});
//Room Schema
var RoomSchema = new AbstractEntitySchema();
RoomSchema.add({
name: {type: String, required: true},
author: {type: String, required: false},
messages : [MessageSchema],
});
var Message = mongoose.model('Message', MessageSchema);
var Room = mongoose.model('Room', RoomSchema);
// save data to Message and Room
var aMessage = new Message({
entityName: 'message',
text: 'Hello',
author: 'mmj',
type: 'article'
});
var aRoom = new Room({
entityName: 'room',
name: 'Room1',
author: 'mmj',
type: 'article'
});
aRoom.save(function(err, myRoom) {
if (err)
console.log(err);
else
console.log("room is saved");
});
aMessage.save(function(err) {
if (err)
console.log(err);
else
console.log('user is saved');
});
这篇关于继承猫鼬模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!