Navigating through various tables (documents) using angularjs and mongoose

I am working towards implementing a setup in mongoDB where each user has their own table (collection of documents). How can I dynamically switch between tables during runtime, based on the user who is logged in? I currently have this code snippet...

var mongoose = require('mongoose'), Schema = mongoose.Schema;

var TicketSchema = new Schema({
  Unit_descriptor: String,
     ...
  Total_tons: Number
}, { strict: false });

module.exports = mongoose.model('tickets_user1', TicketSchema);

...and my goal is to be able to switch the table for the current user, perhaps by appending the username as a suffix to the table name.

I attempted to create an exported function that could be called later from the controller to swap the table, like so:

var auth = require('../../auth/auth.service.js');
...
module.exports.initTable = function initTable() {
    module.exports = mongoose.model('tickets_user2', TicketSchema);
};

However, this approach did not result in the tables being swapped, and data for user1 is still present. Can someone provide guidance on how I can accomplish this? Thank you.

Answer №1

To solve this issue, I customized the second model in the following way:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const TicketSchema = new Schema({
  Unit_descriptor: String,
  ...
  Total_tons: Number
}, { strict: false });

let table = '';

function loadUserTable(user){
  const userTable = user.table;
  if(userTable !== undefined) {
    table = userTable;
  }
  return mongoose.model(table, TicketSchema, table);
}

exports.loadUserTable = loadUserTable;

Then, whenever required, I simply import it and execute the predefined function:

Ticket = require('./loaduser.model');
Ticket = Ticket.loadUserTable(username);

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

Error encountered with auto-generated keys in Angular while using Breeze and MongoDB

Using Breeze with Angular and MongoDB has been my recent project. To ensure seamless integration, I have meticulously added all the required services and scripts for Breeze to work flawlessly with Angular and MongoDB. Despite my efforts, encountering an ...

What is the best way to bring Axios into the main.js file in a Vue project?

Recently, I encountered an issue with using axios in my Vue project. An error message stating that 'axios' is not defined popped up when I attempted to use axios.get() in my Home.vue file. I'm wondering if the problem lies within my configur ...

Incorporate numerous elements using AngularJS

Hey there, I've run into a little issue with my code. I've created a button to add elements to a list, but it only adds one object at a time. How can I make it so that each click on the button adds a new object to the list? Here's the HTML: ...

Having difficulty invoking JavaScript code from PHP

When a button is clicked, this Javascript function is triggered: var xmlhttp; function register() { xmlhttp=GetXmlHttpObject(); alert("pass"); if(xmlhttp==null) { alert("Your browser does not support AJAX!"); return; ...

Is there another option besides PHP not being compatible with JavaScript?

I'm looking to dynamically change the properties of a div, so I've turned to using the jquery.keyframes plugin. The second class currently has a low-res blurred background image from the croploads directory. Now my goal is to switch it out for a ...

Bootstrap modal with sticky-top class displays abnormal margin and padding upon being shown

Whenever I launch a bootstrap modal, I notice unexpected side padding or margin appearing on certain HTML elements. For instance: Before displaying the modal: <div id="fixedMenu" class="d-none container-fluid menu sticky-top px-0" s ...

Removing quotes from specific JSON values using JavaScript/jQuery

Currently, I am receiving the following data from an ajax call: "nodes": [ {"ID":"87","score":"-0.2","dscore":"-0.4","x":"250","y":"250","name":"TEST","ticker":"TEST","datafrom":"0000-00-00","r":"28","fixed":"true","color":"grey"} ...

Changes are being made to how Date objects stored in Firestore behave, which could potentially cause disruptions in your app

Currently encountering an issue while working on VueJs where I am struggling to log data from Firebase. Despite making code adjustments based on the console's recommendations, nothing seems to be working as expected. My setup involves using Vue Cli 3 ...

What is the process for playing an audio file on a mobile device?

Recently, I encountered an issue with a jQuery statement that plays a created audio file. Strangely, the file plays correctly on my computer but not on my mobile phone. Despite max volume settings, there is no sound when trying to play it on the mobile dev ...

How can we enhance the efficiency of rendering text on the screen?

Imagine having a <p> tag inside a <div> with specific properties: div { height: 100px; width: 100px; overflow: hidden; } My goal is to continuously add words to the <p> tag until an overflow is detected, meaning stop when the f ...

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

extract information from the request header

One of the functionalities in my application involves making Ajax requests to the server. $.ajax({ type: "get", beforeSend: function (jqXHR) { jqXHR.setRequestHeader(ZO_KEY1, _key1); jqXHR.setReq ...

There seems to be a syntax error in the Textillate Plugin, where an IntegerLiteral was expected but ""

I am currently incorporating the Textillate plugin for text animation in my web application. However, I am encountering a Syntax error in Eclipse when defining the JavaScript for the animation, particularly with the 'in' definition. How can I res ...

Leveraging Fetch in React for retrieving information from a server

Attempting to retrieve data from the server (using Node.js) using the code below: componentDidMount = () => { fetch('http://localhost:3000/numberofjobs') .then(response => response.json()) .then(numberOfJobs => { console.log(numbe ...

Learn how to extract data from the "this" object in JavaScript

Can anyone help me with retrieving the numbers generated by this code snippet? $("#100wattaren") .countdown("2018/01/01", function(event) { $(this).text( event.strftime('%D days %H hours %M minutes %S seconds') ); }); When I con ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

Issue with socket.io and crypto.js communication

My previous Socket.IO example was quite simple, but it stopped working after I updated to Socket.IO 0.6.1 (installed with npm) and node.JS 0.5.0-pre (without ssl). Within transports/websocket.js:128:22, there is an attempt to use crypto.js:101 [return new ...

Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL: cars : valid cars/ : valid (Accepting any number of '/' after "cars") cars- : invalid cars* : invalid carsp : invalid (Rejecting any character after "cars" except '/') **cars/ne ...

Error message "Slice of undefined" occurs while attempting to use pagination within an ng-repeat loop

My goal is to implement pagination on the ng-repeat results in my list. I want to display only 2 results initially and then have next and previous buttons that function accordingly. This is the code for my controller: <script> var app = angular ...

Displaying live data from a spreadsheet directly on a sidebar

My goal is to extract data from another sheet in the same spreadsheet and present it as a dropdown selection in the sidebar. The code.gs file contains a function called getVisualData() that successfully retrieves the desired list: function getVisualData() ...