What is the process for dynamically including a document in a collection?

I am currently developing an accounting system that allows users to dynamically create accounts in the chart of accounts. Each time a new account is created, the app also generates a new collection for that specific account. Here is an example:

    const account = new Chart({
    name: accountName,
    category: accountCategory
});

After creating the account and adding it to the charts collection, I need to create a separate collection for that specific account. I attempted to call a new method to accomplish this, which looks like:

const createModel = (accountName)=>{
const newModel = mongoose.model(accountName, ledgerSchema);
}

This successfully creates a model, and I can immediately add a document to it as shown below:

const createModel = (accountName)=>{
const newModel = mongoose.model(accountName, ledgerSchema);
const record = new accountName({
some_value: 100
});
record.save();
}

The issue arises when I try to create documents and add them to the model at a later point or in another function, as it only seems to work during the model declaration phase. If I attempt to do the following:

const record = new accountName({
some_value: 100
});
record.save();
}

In any other function or after the application has been closed, it fails with the error message stating that accountName is not defined. Assistance would be greatly appreciated.

Answer №1

To ensure efficiency, you should continue using the existing model until the connection is closed. If the connection closes, then you will need to create a new instance. For further information, please visit this link.

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

Assigning path handlers to external modules in NodeJS using Express

I've been trying to minimize the complexity in my routes.js file. Check it out: module.exports = function(app, db) { app.get('/', function(req, res) { res.render('index') }); app.get('/contact-us', function(req, re ...

Is it possible to keep the screen in the same position using Javascript or jQuery, even after refreshing the page?

On my page for live scores results, there are two sections - the top section displays live match results and information, while the bottom section is dedicated to comments. When I submit a comment, the page refreshes and goes back up to the information sec ...

Can you provide instructions on utilizing the async .update() function for DataTables within MDBootstrap?

I am just starting to explore MDBootstrap and I'm currently focused on grasping how to utilize the DataTables. While I've browsed through the examples on their website regarding Async table updates, I've found it a bit challenging to adapt i ...

What is the best way to ensure that each iteration of a loop completes before moving on to the next one?

Hey there, I'm working on implementing a nested forEach loop. The challenge is to ensure that the outer loop doesn't move to the next iteration until the inner loop has completed its execution. I attempted using async.forEachOf, but found that th ...

Is my rtk slice's initial state not being saved correctly in the store?

Currently diving into the world of RTK with typescript. I have created 2 slices - one using RTK query to fetch data (called apiSlice.ts) and another utilizing createSlice for handling synchronous state changes in my todo app (named snackbarSlice.ts). The ...

The basic generator appears to be malfunctioning

Recently, I created a basic generator: function geni() { for(var i = 0; i < 10; i++) { yield i; } } Unfortunately, I encountered an error message: SyntaxError: missing ; before statement [Break On This Error] yield i; My devic ...

PHP Instant Chat Improvements

I am in the process of developing a messaging system that consists of the following components: A form that allows users to send messages, with PHP handling the insertion of data into a MySQL Table named userMessages upon submission. A PHP page that ...

Gulp: executing a task with no specified output location

I am attempting to create a straightforward task to display the file size for each file in an array of paths using the gulp-size plugin, as shown below: var gulp = require('gulp') var size = require('gulp-size') gulp.task('size&a ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

Concurrent execution within a Node.js function

I am facing a challenge with my function that deals with 1400+ crypto pairs. Each pair requires an API call and data storage, resulting in a significant amount of time for the entire process. The bottleneck occurs because each pair takes approximately 3-4 ...

Creating a personalized contact form with a mailto link that also includes the ability to automatically copy information into the email

I'm in the process of developing a basic contact form that includes input fields for name and subject, as well as a send button (which is an <a> element inside a <div>. I am utilizing an <a> tag because I intend to use mailto functio ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Getting an object from a MongoDB Array: A comprehensive guide

I need assistance in retrieving a single object from an array stored in a mongoDB database. Here is a snippet of how the collection looks like : [ { _id: "60313c2de6ae000124b6626e", title: "<p>yyyyyyyyy</p>", ...

How can I extract a specific term from a list separated by commas?

How can I extract the phrase green eyes from a string that is separated by commas, like in this example: young lady , beautiful , green eyes , wearing shirt , wearing necklace I specifically want to extract the term eyes, for instance. What would be the ...

Invoking a function prior to the callback function being executed

I am currently developing a to-do app and facing an issue with running a specific function before the callback function returns its output. The callback function is triggered by a click event and displays the user's input value on the screen. However, ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

Using Jquery to retrieve the selected value from a dropdown menu

Here is the HTML code I am using for a dropdown list: <select id="dd"> <option>Select ReportType</option> <option value="1">Blocked Details</option> <option value="2">Supervisor Input</option> </ ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...