【发布时间】:2016-12-05 17:54:38
【问题描述】:
我只想在 MongoDB 中拥有一个 versioneditems 集合,但我需要同时注册 VersionedItem 模型和 ItemPatch 模型,因为我需要创建 ItemPatches 来填充 VersionedItem。
不会有单独的ItemPatch 文档(它们嵌入在VersionedItem 中)。除了在 MongoDB 中创建了一个额外的集合之外,下面的代码可以正常工作:
src/models/versionedItemFactory.js
const VersionedItemSchema = require('../schemas/VersionedItem');
module.exports = (db) => {
var VersionedItemModel = db.model('VersionedItem', VersionedItemSchema);
return VersionedItemModel;
};
src/models/itemPatchFactory.js
const ItemPatchSchema = require('../schemas/ItemPatch');
module.exports = (db) => {
var ItemPatchModel = db.model('ItemPatch', ItemPatchSchema);
return ItemPatchModel;
};
src/schemas/util/asPatch.js
var mongoose = require('mongoose');
module.exports = function _asPatch(schema) {
return new mongoose.Schema({
createdAt: { type: Date, default: Date.now },
jsonPatch: {
op: { type: String, default: 'add' },
path: { type: String, default: '' },
value: { type: schema }
}
});
};
src/schemas/Item.js
var mongoose = require('mongoose');
module.exports = new mongoose.Schema({
title: { type: String, index: true },
content: { type: String },
type: { type: String, default: 'txt' }
}, { _id: false });
src/schemas/ItemPatch.js
var asPatch = require('./util/asPatch');
var ItemSchema = require('./Item');
module.exports = asPatch(ItemSchema);
src/schemas/VersionedItem.js
var mongoose = require('mongoose');
var ItemPatchSchema = require('./ItemPatch');
module.exports = new mongoose.Schema({
createdAt: { type: Date, default: Date.now },
patches: [
{
createdAt: { type: Date, default: Date.now },
jsonPatch: { type: ItemPatchSchema }
}
]
});
然后像这样注册:
db.once('open', function() {
require('./models/itemPatchFactory')(db);
require('./models/versionedItemFactory')(db);
});
我需要通过itemPatchFactory 注册ItemPatch 模型,因为我希望能够像这样填充版本化项目:
var itemPatch = new db.models.ItemPatch({
jsonPatch: {
op: 'add',
path: '',
value: {
title: 'This is a title',
content: 'This is content',
type: 'txt'
}
}
});
var itemPatch2 = new db.models.ItemPatch({
jsonPatch: {
value: {
title: 'This is a title 2',
content: 'This is content 2'
}
}
});
var versionedSomething = new db.models.VersionedItem();
versionedSomething.patches.push(itemPatch);
versionedSomething.patches.push(itemPatch2);
versionedSomething.save(function (err, result) {
if (err) throw err;
console.log('result:', result);
});
这成功创建了其中包含 2 个补丁的版本化项目,但在 MongoDB 中创建了一个(空的)itempatches 集合,我想避免这种情况。
【问题讨论】:
-
我也想要这个。
标签: mongoose