Verify in Mongo if a specific document is already present

Currently in development of my MEAN app, the client-side sends a $http POST request to my API with a JSON array containing soundcloud track data specific to each user. My goal now is to save these tracks to my app database within a 'tracks' table. This will allow me to load the tracks for the user from the database and also create unique client URLs like (/tracks/:track)

Here is some sample data:

{
    artist: "Nicole Moudaber"
    artwork: "https://i1.sndcdn.com/artworks-000087731284-gevxfm-large.jpg?e76cf77"
    source: "soundcloud"
    stream: "https://api.soundcloud.com/tracks/162626499/stream.mp3?client_id=7d7e31b7e9ae5dc73586fcd143574550"
    title: "In The MOOD - Episode 14"
}

This data is sent to the API as follows:

app.post('/tracks/add/new', function (req, res) {
     var newTrack;
     for (var i = 0; i < req.body.length; i++) {

        newTrack = new tracksTable({
            for_user: req.user._id,
            title: req.body[i].title,
            artist: req.body[i].artist,
            artwork: req.body[i].artwork,
            source: req.body[i].source,
            stream: req.body[i].stream
        });

        tracksTable.find({'for_user': req.user._id, stream: req.body[i].stream}, function (err, trackTableData) {

            if (err)
                console.log('MongoDB Error: ' + err);

            // stuck here - read below

            });    

        }
    });

I'm currently facing a challenge at this point, as mentioned above: I need to check if the track already exists in the database for that particular user, and if not, then save it. Once all tracks have been processed, either saved or ignored, a 200 response should be sent back to the client.

I've tried various approaches but haven't had success yet. Any help or advice on this matter would be greatly appreciated.

Answer №1

Establish a unique compound index to prevent any duplicate documents containing the same for_user and stream.

trackSchema.ensureIndex( {for_user:1, stream:1}, {unique, true} )

Utilize mongoDB's batch operation to efficiently insert multiple documents at once.

//docs represents an array of tracks ready for insertion.

trackTable.collection.insert(docs, options, function(err,savedDocs){
 //savedDocs contains the successfully inserted documents.
 //Check savedDocs to verify the number of tracks that were actually added.
})

Remember to validate your objects properly since using .collection bypasses mongoose validation methods.

Answer №2

Create a special identifier based on the user and track information to use as a unique _id in MongoDB. You can specify the _id value when inserting a document.

For example, {_id : "NicoleMoudaber InTheMOODEpisode14", artist: "Nicole Moudaber" artwork: "" source: "soundcloud" stream: "? client_id=7d7e31b7e9ae5dc73586fcd143574550" title: "In The MOOD - Episode 14"}

The _id must be unique to avoid inserting duplicate documents with the same _id. This unique _id can also be used to search for records later, like db.collection.find({_id : NicoleMoudaber InTheMOODEpisode14}).

You can also find all tracks related to Nicole Moudaber by using db.collection.find({_id : /^NicoleMoudaber/}), which will utilize the index.

If you prefer a different method, I can explain that as well.

Both of these options are compatible with both sharded environments and single replica sets. Note that "Unique" indexes do not function in a sharded environment.

Answer №3

Utilize the Soundcloud API to obtain a unique track ID. Before proceeding with data insertion, ensure to follow this process:

tracks.find({id_soundcloud : 25645456}).exec(function(err,track){ 
    if(track.length){ console.log("No action required")} else {//continue with insertion}
 });

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

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

A guide to disabling daily checkboxes and retrieving the chosen values using Angular.js

Within a single table, I have incorporated a dynamic drop-down list that spans over 7 days. Additionally, I have implemented a "+" button that allows for the creation of additional rows dynamically for each day. Each row within the table features a checkb ...

Issue with regex replacement behaving differently in Node compared to console

I am having trouble properly escaping commas in a sentence. Oddly enough, my replace method is not functioning correctly in node, while it works fine in the Chrome console. Is there anyone who has a solution to this issue? It seems to be occurring with al ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

Send a PHP array back to jQuery AJAX and dynamically populate a list using conditional statements

Looking to create a dynamic contact list that can be sorted using AJAX. When selecting one of the 3 menu options, a new list with updated information should be displayed. I've been doing some research but haven't come across useful information o ...

What is the reason for jQuery scripts not functioning properly when the scripts are placed above the jQuery library?

this script is functioning correctly: <div class="demo-gallery" data-pswp-uid="1"> <a class = "delete_button">click</a> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <script> ...

What is the best way to dynamically load a personalized JavaScript file for individual users depending on their PHP login credentials?

Currently, I am conducting a web-based experiment in which students log into a website to take practice tests for a class. Initially, the students land on a login page that includes the following code: include_once("core/config.php"); include_once("core/ ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

Reading a JSON file using Javascript (JQuery)

Struggling to figure out how to handle a JSON file using JavaScript. Here are the details : { "streetCity": { "132":"Abergement-Clemenciat", "133":"Abergement-de-Varey", "134":"Amareins" } } I am attempting to access ...

An elusive melody that plays only when I execute the play command

I am currently working on creating a music Discord bot using the yt-search library, however, I am encountering an issue where it returns undefined when trying to play a song and joins the voice channel without actually playing anything. My approach is to u ...

The PassportJS logged in feature always yields a result of zero

After successfully implementing passportJS in my application, I encountered an issue with the current connected user. When using (req.isAuthenticated()), it always returns "0". Here is the code snippet from auth.js: /* Passport - Sessions - Cookies D ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

Struggling with showcasing Trips in my React Native project and looking for guidance on the best approach to implement it beautifully

API: app.get('/trip', async (req, res) => { try { const employeeId = req.query.user; const empId = new ObjectID(employeeId); // Retrieving Fleet associated with the driver's ID const fleet = await Fleet.findOne({ a ...

Is it possible to establish a scope for jquery.ajaxSetup()?

Currently, I am working on a project involving numerous ajax calls with repetitive parameters. After some consideration, I am contemplating using jquery.ajaxSetup() to streamline the code. However, jQuery does not recommend this approach in their API docu ...

Preserving user interaction history in the browser while syncing with the server in AngularJS

My current challenge involves handling an HTML form that is connected to an object named a through an ngModel. When a user updates the data in the form, I send a PUT request to update the resource on the server. The response from the server contains update ...

"Strategies for using Selenium in Python to simulate clicks without relying on class, id, or name attributes

I am currently attempting to locate the "X" button and click on it, but I am struggling to find a way to do so. Below is the HTML code for the element: <div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: ...

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

Troubleshooting issues with environment variables in Next.js version 12.2.2

I tried following the steps outlined in the official documentation, but I'm encountering an issue. Here is what I did: next.config.js const nextConfig = { reactStrictMode: true, swcMinify: true, env : { MORALIS_ID: 'moralisId', ...

Guide on incorporating custom items alongside default items in the Context Menu of Handsontable

I attempted to utilize handsontable and am interested in incorporating custom additions to the context menu. While there are numerous tutorials on how to implement custom menus, they often overlook the default items. In an effort to address this issue, I ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...