Avoid adding duplicate elements by redirecting to the already existing element

Here is my method for adding elements to a list, which contains links to articles, using an input field:

Template.addForm.events({
    'submit form': function(event){
        event.preventDefault();
        var title = event.target.text.value;    
        MongoValues.insert({
            title: title,
            slug: title.toLowerCase()
        }, function(error, result) { if(error) console.warn(error); });
        event.target.text.value = "";
    }
});

I am now working on preventing duplicate entries. If a user wants to add a title that already exists, I want to redirect them to the existing element (route to article/_id) instead of adding the title to the list again.

Answer №1

Suppose you are utilizing iron:router and have a route setup like below :

Router.route('post/:_id', {
    name: 'post'
    // other route configurations
});

To modify your code, consider the following:

Template.createForm.events({
    'submit form': function(event){
        event.preventDefault();
        var title = event.target.text.value; 
        var existingPost = PostCollection.findOne({title : title});
        if (!!existingPost) { 
          // post with the same title exists, navigating to that post
          Router.go("post", {_id : existingPost._id});
        } else {   
          // new post creation as the title does not exist
          PostCollection.insert({
              title: title,
              slug: title.toLowerCase()
          }, function(error, result) { 
            if(error) {
              console.warn(error); 
            }
          });
          event.target.text.value = "";
      }
    }
  });

Please note that this method will not prevent duplicates if someone inserts data directly through the console.

If you are using Collection2 and SimpleSchema, you can enforce uniqueness on the title field by setting "unique: true". Here's an example of how to do so:

title : {
   type: String,
   unique: true
}

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

Utilizing ng-model in AngularJS to add data to an array in Mongoose and MongoDB

I am currently utilizing ng-model to input data into my MongoDB. Is there a method to utilize ng-model to insert data into an array within MongoDB? answers is an array that should include 4 strings entered by the user. I attempted adding [0], [1], [2], [3] ...

"Big Cartel - Effortless File Upload and Geolocation with JQuery

Check out my site here: I've been experimenting with images on my product pages and even created a test page. I have a few questions that I can't seem to figure out: Where should I host a jquery file? Do I need to include the jquery src for b ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

What causes certain event handlers to be activated when using dispatchEvent, while others remain inactive?

When it comes to event-based JS, there are two main APIs to consider: event listeners and event handlers. Event listeners can be registered using addEventListener, while event handlers are typically registered with an API similar to target.onfoobar = (ev) ...

The occurrence of an unhandled promise rejection is triggered by the return statement within the fs

In my code, I have a simple fs.readFile function that reads data from a JSON file, retrieves one of its properties (an array), and then checks if that array contains every single element from an array generated by the user. Here is the snippet of code: co ...

Is it possible to retrieve the value of this input field within a function call in HTML?

When working with an HTML input field, I encountered the need to limit manual input to 100. Although I already had minimum and maximum values set up for spinner functionality (up and down arrows), I wanted to create a reusable function instead of using inl ...

Retrieve the ID of the moped after it has been inserted into the

After using the mongo-ruby-driver to insert a new document, it generates an '_id': db = MongoClient.new('127.0.0.1', '27017').db('ruby-mongo-examples') id = db['test'].insert({name: 'example'}) ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

PHP implementation of MongoDB Upsert causing unexpected issues

I'm currently attempting to update my documents using the upsert true method, but it seems to be overwriting instead. Any suggestions? $col = "A" . $user->agencyID; $db = $m->rules; $collection = $db->$col; $validValue = $_POST['validV ...

Using the $addToSet operator in Mongoose to create unique elements

I'm trying to achieve something similar to the following: Code.create({ childCode: {"$addtToSet": code.child}, parentCode: code.parent } Unfortunately, it doesn't seem to be working. Is there a solution for this? ...

Numerous Levels of Dropdown Menus

I am looking to implement a feature on a web page where users can select multiple vehicles using JQuery. The idea is that selecting the brand in the first dropdown will populate the second dropdown with the models available for that specific brand. The ...

The utilization of ReactJS to render basic HTML elements

Completely new to react, I'm not sure if my code is written the "react way". Created some react classes rendering a Bootstrap Modal. Set the initial states by calling an Ajax function within componentsDidMount. Everything works until trying to insert ...

I'm struggling to solve a straightforward jQuery sliding issue

I am struggling to make text slide from right to left on my website. I want the text to appear only when the page loads or refreshes, and then slide off when a link is clicked, revealing new text. Can anyone help me figure this out? http://jsfiddle.net/XA ...

Unleashing the Power of Javascript in Selenium with Java (featuring PrimeFaces)

Recently, I discovered that JavaScript seems to be malfunctioning in my Selenium Tests written in Java. The reason behind this issue remains a mystery to me. Any ideas on how to tackle this roadblock? ((JavascriptExecutor) driver).executeScript("retur ...

The second AJAX request isn't functioning properly; it should only be executed once the first one has successfully completed

I am experiencing an issue with my ajax calls. The second call should only be triggered after the first one is successful. However, even though the first call always returns success, I keep getting an error for the second one. function proceedWithUnlock(t ...

Retrieving information by comparing various criteria in MongoDB databases

I am looking to retrieve data only when all the specified queries align perfectly. Below is the query for fetching the data: exports.getParkingListByCriteria = async (req, res) => { const cityQuery = req.body.city; const stateQuery = req.body.state ...

SailsJS - handling blueprint routes prior to configuration of routes

I am trying to configure a route in my config/routes.js file as shown below '*' : { controller: 'CustomRoutes', action: 'any', skipAssets:true } The CustomRoutes controller is responsible for handling custom routes. Th ...

Using JavaScript to control the state of a button: enable or

In the process of creating a basic HTML application to collect customer information and store it in a database, I have encountered a specific user interface challenge. Once the user logs into their profile, they should see three buttons. Button 1 = Print ...

Guide to utilizing the XHR API in a Node.js environment

I am writing to elaborate on a previous discussion I had found here. Imagine that I have some javascript code that functions smoothly on the client side (within a browser). This particular code involves numerous XHR calls using the browser API. My curren ...

What benefits does JavaScript offer with the strategy of storing functions within variables?

Lately I've come across some code where functions are being stored inside variables and then called in the typical way. For example: var myFunctionName = function() { Code Here... } myFunctionName(); I'm aware that there may be numerous b ...