通过Mongoose在MongoDB中存储嵌入到另一个文档中的文档副本 [英] Storing a copy of a document embedded in another document in MongoDB via Mongoose

查看:123
本文介绍了通过Mongoose在MongoDB中存储嵌入到另一个文档中的文档副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要将Mongo文档的副本作为嵌入的子文档存储在另一个文档中.它应该参考原始文档.复制的文档需要是深层副本,例如原始文档的快照.

We have a requirement to store a copy of a Mongo document, as an embedded subdocument in another document. It should have a reference to the original document. The copied document needs to be a deep copy, like a snapshot of the original.

原始文档的架构(用Mongoose定义)不是固定的- 它当前使用一种继承类型,以允许根据类型"对架构进行不同的添加.

The original document's schema (defined with Mongoose) is not fixed - it currently uses a type of inheritance to allow different additions to the Schema depending on "type".

  1. 在Mongoose模型中是否有这样一种灵活的嵌入式架构的方法?
  2. 当我们知道时,是否需要在运行时注入某些东西 模式?
  1. Is there a way to such a flexible embedded schema within a Mongoose model?
  2. Is it something that needs to be injected at runtime, when we can know the schema?


我们当前拥有的模型/模式如下:


The models / schemas we have currently look like this:

///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'
}   


我们当前使用的代码使用继承来允许不同的项目类型.我意识到这种技术可能不是实现我们所需灵活性的最佳方法,也不是我关注的重点.


The code we currently have uses inheritance to allow different item types. I realise this technique may not be the best way to achieve the flexibility we require and is not the focus of my question.

///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;

推荐答案

我认为您只需要为父级猫鼬模式中的文档创建一个空的{}对象即可.这样,您将能够使用任何数据的硬拷贝存储任何对象.

I think you just need to create an empty {} object for the document in your parent mongoose schema. This way you´ll be able to store any object with a hardcopy of all it´s data.

parentobj : {
    name: Sring,
    nestedObj: {}
}

我想在这一点上,您需要做的是在保存之前将嵌套的对象标记为已修改.这是我的猫鼬代码的示例.

I think at this point, what you´ll need is to mark your nested objet as modified before you save it. Here is an example of my mongoose code.

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中需要一系列不同的文档,则正确的方法是:

In addition, if you need an array of different documents in nestedDocument, the right way is this one:

parentobj : {
    name: Sring,
    nestedObjs: [Schema.Types.Mixed]
}

请仔细检查猫鼬模式类型

编辑

正如您所说,我将为您添加最终解决方案,其中将ItemSchema包含在nestedObj数组定义中,以将对象的类型澄清为确定的对象的类型.

As you said, I´ll add you final solution as including ItemSchema in the nestedObj array definition to clarifythe type of the object to a determined one..

var ItemSchema = new Schema({
    item1: String,
    item2: String
});

var parentobj = new Schema({
    name: Sring,
    nestedObj: [ItemSchema]
});

请记住,将新项目添加到nestedArray中,必须使用nestedArray.push(item)

EDIT 2: Remember adding new Items to the nestedArray, must be done with nestedArray.push(item)

致谢!

这篇关于通过Mongoose在MongoDB中存储嵌入到另一个文档中的文档副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆