我们需要将Mongo文档的副本存储为另一个文档中的嵌入子文档。它应该引用原始文件。复制的文档必须是深拷贝,就像原始文档的快照一样。
原始文档的架构(用猫鼬定义)不是固定的 -它当前使用一种继承类型来允许根据"类型"对架构进行不同的添加。
- 有没有办法在猫鼬模型中实现如此灵活的嵌入式模式?
- 它是需要在运行时注入的东西,当我们知道时架构?
我们目前拥有的模型/模式如下所示:
///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;
我认为您只需要在父猫鼬架构中为文档创建一个空的 {} 对象。通过这种方式,您将能够存储任何对象及其所有数据的硬拷贝。
parentobj : {
name: Sring,
nestedObj: {}
}
我认为在这一点上,您需要在保存之前将嵌套对象标记为已修改。这是我的猫鼬代码的一个例子。
exports.update = function(req, res) {
User.findById(req.params.id, function (err, eluser) {
if (err) { return handleError(res, err); }
if(!eluser) { return res.send(404); }
var updated = _.merge(eluser, req.body);
//This makes NESTEDDATA OBJECT to be saved
updated.markModified('nestedData');
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, eluser);
});
});
};
此外,如果你需要在nestedDocument中有一个不同文档的数组,正确的方法是这个:
parentobj : {
name: Sring,
nestedObjs: [Schema.Types.Mixed]
}
请仔细检查猫鼬模式类型
编辑
正如您所说,我将为您添加最终解决方案,即在嵌套的 Obj 数组定义中包含 ItemSchema,以阐明对象的类型
以确定的类型。var ItemSchema = new Schema({
item1: String,
item2: String
});
var parentobj = new Schema({
name: Sring,
nestedObj: [ItemSchema]
});
编辑2:请记住,将新项目添加到 nestedArray,必须使用 nestedArray.push(item) 完成
问候!!