【发布时间】:2015-06-20 00:56:52
【问题描述】:
我们需要将 Mongo 文档的副本存储为另一个文档中的嵌入子文档。它应该有对原始文件的引用。复制的文档需要是深层副本,例如原始文件的快照。
原始文档的架构(使用 Mongoose 定义)不固定 - 它目前使用一种继承类型来允许根据“类型”对 Schema 进行不同的添加。
- 有没有办法在 Mongoose 模型中实现如此灵活的嵌入式架构?
- 是不是需要在运行时注入,什么时候才能知道 架构?
我们目前拥有的模型/模式如下所示:
///UserList Schema: - this should contain a deep copy of a List
user: {
type: ObjectId,
ref: 'User'
},
list: {
/* Not sure if this is a how we should store the reference
type: ObjectId,
ref: 'List'
*/
listId: ObjectId,
name: {
type: String,
required: true
},
items: [{
type: ObjectId,
ref: 'Item'
}]
}
///List Schema:
name: {
type: String,
required: true
},
items: [{
type: ObjectId,
ref: 'Item'
}],
createdBy: {
type: ObjectId,
ref: 'User'
}
我们目前拥有的代码使用继承来允许不同的项目类型。我意识到这种技术可能不是实现我们所需灵活性的最佳方式,也不是我问题的重点。
///Item Model + Schema
var mongoose = require('mongoose'),
nodeutils = require('util'),
Schema = mongoose.Schema,
ObjectId = Schema.Types.ObjectId;
function ItemSchema() {
var self = this;
Schema.apply(this, arguments);
self.add({
question: {
type: String,
required: true
}
});
self.methods.toDiscriminator = function(type) {
var Item = mongoose.model('Item');
this.__proto__ = new Item.discriminators[type](this);
return this;
};
}
nodeutils.inherits(ItemSchema, Schema);
module.exports = ItemSchema;
【问题讨论】:
-
问题格式很好!
-
只是出于好奇:这个要求从何而来?在我看来,这是非常无用的数据冗余。
-
通常是这样,但在这种情况下,我们需要复制当时存在的一些数据,因为源数据可能会更改。重要的是,用户拥有当时存在的数据副本。
-
我为计费应用做了同样的事情,允许维护数据的完整硬拷贝。之后,当用户列出它的数据时,尽管用户进行了新的配置,但一切都是如此。