Saving an embedded document within another document in MongoDB using Mongoose

Our project requires us to save a duplicate of a Mongo document as a nested subdocument in another document. This copy should have a direct link to the original document and needs to be a complete replica, like taking a snapshot of the original data.

The schema of the original document (defined using Mongoose) is dynamic - it currently employs a form of inheritance to allow for different additions to the schema based on the "type" property.


  1. Is there a way to implement such a flexible embedded schema within a Mongoose model?
  2. Should this be injected at runtime, when we are aware of the schema?

Here are our current models/schemas:

///UserList Schema: - containing a deep copy of a List
user: {
    type: ObjectId,
    ref: 'User'
},
list: {
    /* Unsure about storing the reference this way
    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'
}   

Currently, our code utilizes inheritance to support various item types. However, I acknowledge that this approach may not be ideal for achieving the level of flexibility we need, which is not the main focus of my inquiry.

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

Answer №1

If you want to store any object with all its data, create an empty {} object within the parent mongoose schema for the document.

parentobj : {
    name: String,
    nestedObj: {}
}

To properly save your nested object, mark it as modified before saving. Here is an example using mongoose:

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

If you need an array of different documents in nestedDocument, use this format:

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

Refer to Mongoose Schema Types for more information.

EDIT

For a specific type of object in the nestedObj array, define an ItemSchema and include it in the schema like so:

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

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

EDIT 2: Remember to add new items to the nestedArray using nestedArray.push(item).

Regards!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Jenkins, there do not exist any configurations specifically for NodeJS installations

I've been struggling with this issue for a while now and haven't been able to find a solution online. Using Jenkins as my CI tool and Git as the source of code. The build trigger is set to another build stability. The plugin manager indicates th ...

What are some methods to display search outcomes in mongodb?

I have created a Comment Model with specific fields including userId, contentId, repliedTo, and text. The schema for the Comment Model is defined as follows: const CommentSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId ...

Utilizing a dynamic form action connected to an Express route

I've been grappling with creating an HTML form in my nodejs application that directs to the appropriate express route upon submission. After researching online, I stumbled upon a potential solution as outlined below: <script> $('#controlPa ...

Production pages encounter 'get' error when refreshed due to routing issues - Node.js, Express API with webpack and ReactJS frontend

I have set up my webpack configuration to compile my react app, and I am using Node.js as the server with Express middleware. Whenever I try to refresh a route on the production environment, for example /chefs, I receive an error. Below is my server.js s ...

Extracting cookie data from a WebSocket query

Currently, I am utilizing Node.js along with WebSocket-Node to develop a WebService. My objective is to link the WebSocket connection to a user ID by accessing the cookie or session details from the web server. I am aware that the cookie information is tra ...

Should using module.export = [] be avoided?

Having two modules that both need access to a shared array can be tricky. One way to handle this is by creating a separate module just for the shared array, like so: sharedArray.js module.exports = []; In your module files, you can then use it like this ...

Receiving information within an Angular Component (Profile page)

I am currently developing a MEAN Stack application and have successfully implemented authentication and authorization using jWt. Everything is working smoothly, but I am encountering an issue with retrieving user data in the Profile page component. Here ar ...

What is the method for receiving socket emits in sails.io.js?

I am currently utilizing Sails 0.11 for the back-end and angularjs for the front-end of my project. Within Sails, I have a TwitterController containing the following code snippet to establish a connection with the Twitter Streaming API using the node modu ...

What are the potential obstacles hindering the functionality of my update route?

I am facing an issue with my node app where it works smoothly, but the put request to update a post is not functioning correctly. Here is what the route looks like: Your valuable answers would be highly appreciated. Even after changing the identifier "p ...

"Make sure to close the serial connection with Arduino's serial port before proceeding with

Trying to utilize node.js to display the Serial data from an Arduino Uno connected via USB. The file script.js contains the following code: var SerialPort= require("serialport"); SerialPort.list(function(err,ports){ ports.forEach(fun ...

interrupt the node script using async behavior

I encountered an issue while running the npm install command to install a list of modules on Node, specifically related to async. TypeError: undefined is not a function What could be causing this problem? var fs = require( "fs" ), path = require( ...

Creating a Docusaurus documentation using Docker: A step-by-step guide

Is it possible to create a Docusaurus-based documentation solely using Docker as the local development environment? If so, how can this be achieved? ...

Error: Unable to access attributes of an unknown variable (retrieving 'use')

I encountered an issue (TypeError: Cannot read properties of undefined (reading 'use')) while trying to execute the 'node server.js' command in the Terminal. The error points to my auth.routes.js file. This is the content of my 'a ...

Having trouble retrieving the API URL id from a different API data source

For a small React project I was working on, I encountered a scenario where I needed to utilize an ID from one API call in subsequent API calls. Although I had access to the data from the initial call, I struggled with incorporating it into the second call. ...

Encountered an issue loading next.config.js during the build process with GitHub actions

Currently, I am utilizing a straightforward ssh deploy action along with a bash script designed to both build and restart the pm2 frontend process. Everything seems to be running smoothly when executing the script directly on the ec2 instance. However, is ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

I am attempting to install Mongoose into my Node.js application using the NPM package manager

D:\all Node place\nodejs\demo-app>npm install mongoose npm ERR! Unexpected end of JSON input while parsing near '...~8.4.1","highland":"^' npm ERR! A complete log of this run can be found in: npm ERR! C: ...

Error encountered in pre-middleware hooks when querying Mongoose model with findById due to foreign model reference

Within this scenario, I have two distinct models: Protocol and Comment. Each model incorporates a middleware ('pre' or 'remove') that triggers the other model. The issue arises when attempting to call the Comment middleware in Comment.j ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

Implementation of async operations using while loop in Node.js

I'm facing an issue with my code snippet. Here's what it looks like: Rating.find({user: b}, function(err,rating) { var covariance=0; var standardU=0; var standardV=0; while (rating.length>0){ conso ...