Mih*_*ela 10 mongoose mongodb node.js
我想创建一个基础'Entity Schema',其他模型实体将继承它.我做到了,有点儿,但后来发生了奇怪的事情.
这些是我的模式:
文件:https://github.com/mihaelamj/nodechat/blob/master/models/db/mongo/schemas.js
但是在MongoDB中,它们都保存在同一个文档存储中:"实体模型"不是单独的文档存储,如消息,用户..我是否得到了应该发生的事情,但不是我想要的,单独的商店?如果是这样,我将只生成一个基本的JSON /对象作为实体,并为每个实体附加适当的属性.或者,还有更好的方法?谢谢.
Discriminators是一种模式继承机制.它们使您能够在同一个基础MongoDB集合之上拥有多个具有重叠模式的模型.而不是不同的文件.你似乎误解了discriminators猫鼬.这篇文章可以帮助您正确捕捉它.
以下是一些符合您要求的代码示例,将派生架构保存为单独的文档
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');
});
Run Code Online (Sandbox Code Playgroud)
如果您想要多个具有不同 MongoDB 集合的重叠模型,那么您可以使用这种方法:
function extendSchema (Schema, definition, options) {
return new mongoose.Schema(
Object.assign({}, Schema.obj, definition),
options
);
}
Run Code Online (Sandbox Code Playgroud)
例子
const extendSchema = require('mongoose-extend-schema');
const UserSchema = new mongoose.Schema({
firstname: {type: String},
lastname: {type: String}
});
const ClientSchema = extendSchema(UserSchema, {
phone: {type: String, required: true}
});
Run Code Online (Sandbox Code Playgroud)
您只需扩展创建模式时使用的原始对象,并在其基础上重新创建新模式。这是您继承的某种抽象模式。
检查这个 npm 模块:https ://www.npmjs.com/package/mongoose-extend-schema
从 ES6 开始,这也有效:
var ImageSchema: Schema = new Schema({
...CommonMetadataSchema.obj,
src: String,
description: String,
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5413 次 |
| 最近记录: |