Is it possible to modify the collection name while saving data in MongoDB?

Is it possible to change the name of the collection where I store the data? I have a Game model and currently save data like this:

const teamData = new Game({
        id: id,
        homeTeamName: hTeam,
        awayTeamName: aTeam,
        homeTeamGoals: homeTeamGoals,
        awayTeamGoals: awayTeamGoals })

  teamData.save()

It saves in the "Games" collection every time, but can I use the same model for different collections? For example, I have games from England, Germany, etc. Do I need a separate model for each country or can I specify the collection name when I use .save()?

Answer №1

There are two ways you can approach this situation

  1. To begin, include an additional field country in your Model like so:

    const teamData = new Game({
    id: id,
    homeTeamName: hTeam,
    awayTeamName: aTeam,
    homeTeamGoals: homeTeamGoals,
    awayTeamGoals: awayTeamGoals,
    country: country})
    
  2. Alternatively, create a separate collection named Countries where each document contains details specific to a particular country, storing the corresponding country's id in your Game Model.

Answer №2

When it comes to documentation, utilizing the model() method is recommended. Instead of using a string name, you can pass a class that extends Model.

Your generic schema would be named teamSchema.

const teamSchema = new Schema({
    id: string,
    homeTeamName: string,
    awayTeamName: string,
    homeTeamGoals: number,
    awayTeamGoals: number
})

To store a document in different collections, create a model for each instance:

const germanyModel = db.model('germany', new Game({
    id,
    homeTeamName: hTeam,
    awayTeamName: aTeam,
    homeTeamGoals,
    awayTeamGoals
}));

germanyModel.save()

If you want to automate this process, you can use a string variable to specify the collection name:

const collection = 'spain';
const dynamicModel = db.model(collection, new Game({
    id,
    homeTeamName: hTeam,
    awayTeamName: aTeam,
    homeTeamGoals,
    awayTeamGoals
}));

dynamicModel.save()

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

Visibility of Code in AngularJS

After inspecting the source code of a website built with Angular today, I came across a snippet that made me ponder whether it's advisable to have such elements visible to everyone. ul class="nav-account desktop-only" ng-show="!User.isAuthenticated" ...

Submit button in React form not activating the onSubmit method

Having an issue with a login form code where the submit handler is not being triggered when pressing the Submit button. Any idea what could be causing this? The loginHandler function does not seem to trigger, but the handleInputChange function works fine. ...

What is the best way to pass data from the server to a Vue CLI application?

I am looking for a way to connect my Vue CLI app to a server back-end. The server will send a view template along with data payload, and I need to inject that payload as JSON into the Vue app as a data property. Here is a snippet of the index.html file ge ...

Converting JSON data from a PHP variable into a jQuery array: What you need to know

I attempted to retrieve addresses using the postcode and applied the getaddress.io site API with PHP. This resulted in a JSON dataset stored in the PHP variable $file. Now, I am tasked with converting this JSON result into a jQuery array. { "Latitude":-0. ...

Mastering the art of using $lookup pipeline in MongoDB Aggregation for grouping

I'm dealing with a document that has a field called package, which is an array referencing other documents by their groupid. Below are some examples from the products collection: { _id: ObjectId("5fa***********"), groupid: "ffc6 ...

Establish a timeout period when using the hover function

My dynamically loaded content requires a specific method of invocation due to its unique nature. While the process runs smoothly without using a setTimeout, is there any way to introduce a 0.25 second delay in this scenario? Check out this fiddle for ref ...

Issue with typography upon initial page load

Hey everyone! I recently completed a crash course in html, css, and javascript within just one month. However, I encountered an issue while using canvas to draw text with a custom font. The font didn't load the first time I ran the code, but strangely ...

Analyzing the browser's address bar and creating a navigation link derived from it

Is there a way to create a script that can extract information from the address bar? For example, if we have a link like this: We want to be able to take the "page-2011" part and dynamically generate navigation links like this: « <a href="/page-2010 ...

Looking to retrieve data using Cheerio? If you're finding that the data appears empty in the page source but is visible when inspecting the elements, here's how you can go

I am encountering difficulties while trying to scrape data from another website. In my case, I notice that the data appears empty when viewing the page source, but it is visible when inspecting the elements. If you're confused, please refer to the fol ...

Send a POST request including an audio file and then navigate to a different page

Here is the functionality I have implemented: ./upload: This feature allows users to upload an existing local audio file to ./post_receiver via a POST request. ./post_receiver: Receives the POST request and responds with an HTML page. ./record: Users ca ...

The Math.round() function will round numbers up to the nearest whole number, without specifying decimal places

Check out my code snippet: Math.floor((7/2)*100)/100 The expected output is "3.50", however, it currently outputs "4.00". Can you help me figure out how to round this value without rounding up? ...

Save vast collection of JSON data in MongoDB with the help of Mongoose

Imagine that I have a JavaScript Array called companyBills, containing more than 100,000 elements stored in the following format: {key_0:value_0, key_1:value_0_1, key_n:value_0_n}, {key_0:value_1, key_1:value_1_1, key_n:value_1_n}, {ke ...

Choose the tab labeled "2" within a segment of the webpage

index.html#section takes you to a specific section of a webpage. However, I am interested in picking the second tab within a section of the page. I'm uncertain if this can be achieved without relying on JavaScript, but employing the Tab Content Script ...

Using AJAX and PHP to input data into the database repeatedly

Need help inserting multiple values into a database using Ajax and PHP. Currently, the code only inserts one value and I can't figure out why. PHP Code: $content = $_POST['content']; $text = $_POST['text']; mysql_query("inser ...

Trouble with the width of the message container in CSS styling

I need to display a message at the top-center of my webpage. I have created a simple example for this: http://jsbin.com/eniwax/3/edit The issue I am facing is with the width of the message container. I want the container width to adjust dynamically based ...

Exploring methods for handling svgs incorporated in angular.js templates with webpack

I'm currently working on cache-busting my SVGs and other files like translation JSON. The issue I'm facing is that webpack does not seem to recognize imported svgs in the following format: <md-icon md-svg-src="assets/icons/ic-edit.svg">&l ...

Managing large quantities of JSON-like data within MongoDB

My choice to use MongoDB is driven by the fact that Meteor doesn't officially support any other databases. The ultimate objective is to upload CSV files, parse them within Meteor, and import the data into the database. The size of the inserted data ...

Exploring collision detection in Three.js

I'm fairly new to 3D and Threejs. I've created a scene with a ground, where many cubes are positioned on top of it. http://jsfiddle.net/whurp02s/1/ My goal is to select the cubes that intersect with the yellow rectangle. To achieve this, I re ...

YouTube's embedded video player is invincible and cannot be destroyed

Having trouble destroying an embedded YouTube video on the Plyr player. The player.destroy() method is being called without any errors, but it doesn't actually destroy the player. This issue is causing the previous video to load instead of a new one ...

Identifying the modifications made to a Firestore list, including additions, deletions, and changes

Utilizing Firestore as the backend has allowed me to navigate basic crud methods effectively. However, I am curious about how to identify changes within a list of returned items after the initial subscription. My goal is twofold: - Minimize the number of ...