80907

Storing a copy of a document embedded in another document in MongoDB via Mongoose

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.

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".

<hr> <ol> <li>Is there a way to such a flexible embedded schema within a Mongoose model?</li> <li>Is it something that needs to be injected at runtime, when we can know the schema?</li> </ol> <hr>

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' }] } <hr> ///List Schema: name: { type: String, required: true }, items: [{ type: ObjectId, ref: 'Item' }], createdBy: { type: ObjectId, ref: 'User' } <hr>

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;

Answer1:

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); }); }); };

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] }

Please check Mongoose Schema Types carefully

<strong>EDIT</strong>

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] });

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

regards!!

Recommend

  • How to Check Rating Settings is enabled or not by Javascript in SharePoint 2010?
  • Microsoft Graph update SharePoint list item multi choice field
  • How to implement a search for a ListView that uses ListAdapater, ArrayList and HashMap
  • undefined method 'info' for nil:NilClass when running active record migration
  • Intercepting Outlook category assignment events?
  • Can I deploy Python .pyc files only to Google App Engine?
  • Core Data vs SQLite [closed]
  • create an eventreceiver for logging changes made by users in lists
  • SpringData MongoDB cannot determine IsNewStrategy during Auditing
  • Error: key $$hashKey must not start with '$' (AngularJS)
  • Best way to Update Two common functions to use shared function
  • preg_replace speed optimisation
  • Broadcast advanced indexing numpy
  • Access the state of control in Winforms from another application
  • EntLib Way to Bind “Null” Value to Parameter
  • Azure table store snapshot/backup capability
  • Cast between interfaces whose interface signatures are same
  • How to detect interior vertices in groups of 2d polygons? (E.g. ZIP Codes to determine a territory)
  • Django model inheritance, filtering models
  • Typescript - Unable to get 'import' statement to function
  • C++ Partial template specialization - design simplification
  • How can I send an e-mail from a vbs script
  • Javascript simulate pressing enter in input box
  • Read text file and split every line in MSBuild
  • Align navbar back button on right side
  • Can Jackson SerializationFeature be overridden per field or class?
  • Is possible to count alias result on mysql
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Benchmarking RAM performance - UWP and C#
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • Acquiring multiple attributes from .xml file in c#
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Turn off referential integrity in Derby? is it possible?
  • How can I remove ASP.NET Designer.cs files?
  • Add sale price programmatically to product variations
  • Unable to use reactive element in my shiny app
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How do I use LINQ to get all the Items that have a particular SubItem?