Issue with Backbone: model does not have a defined function for model destruction

Currently facing a TypeError in my JavaScript code related to calling "model.destroy()" on what should be a Backbone model object:

Here is the Backbone code snippet causing the issue:

var Team = Backbone.Model.extend({
    idAttribute: "_id",
    urlRoot: '/api/teams'
});

var TeamCollection = Backbone.Collection.extend({
    model: Team
});

var teamCollection = new TeamCollection([]);
teamCollection.url = '/api/teams';
teamCollection.fetch(
    {
        success: function () {

            console.log('teamCollection length:', teamCollection.length);

        }
    }
);
var UserHomeMainTableView = Backbone.View.extend({
    tagName: "div",
    collection: teamCollection,
    events: {},
    initialize: function () {

        this.collection.on("reset", this.render, this);

    },
    render: function () {

        var teams = {
            teams:teamCollection.toJSON()
        };

        var template = Handlebars.compile( $("#user-home-main-table-template").html());

        this.$el.html(template(teams));

        return this;
    },
    addTeam: function (teamData) {
        console.log('adding team:', team_id);
    },
    deleteTeam: function (team_id) {

        console.log('deleting team:', team_id);
        var team = teamCollection.where({_id: team_id}); //team IS defined here but I can't confirm the type even when logging "typeof"
        console.log('team to delete', typeof team[0]);
        console.log('another team to delete?',typeof team[1]);
        team.destroy({      //THIS FUNCTION CALL IS THROWING A TYPEERROR
            contentType : 'application/json',
            success: function(model, response, options) {
                this.collection.reset();
            },
            error: function(model, response, options) {
                this.collection.reset();
            }
        });
    }
});

The data being fetched from the node.js server is returned as JSON which includes cid's and other properties. The objects in question were previously Backbone models.

The confusion lies in why the type of team is not recognized as a Backbone model.

Any insights or suggestions?

Answer №1

.where will give you an array as a result. It would be better to utilize .findWhere in this scenario.

Another approach is to iterate through the resulting array and call destroy on each model individually.

.where({...}).forEach(function(model){
    model.destroy();
});

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

The height of the article automatically adapts to fit in seamlessly with the

Check out this snippet of Javascript code: for(var i=1;i<4;i++) { var img= ".img"+i; $(img).on("click", function(){ var art = $(this).closest('article'); art.css('height', 'auto&apo ...

Determining the Day Difference Between Two Dates using DataWeave

Within a JSON response, there are two dates provided: "startDate": "2017-04-30" and "EndDate": "2017-05-27". These dates have been transformed into dataweave as dates. I am looking to calculate the number of days between these two dates. Is there a speci ...

"Encountering an error in Vue3 CompositionAPI: 'quizz is not defined' while trying to call a function from the

When attempting to call a function, I am encountering an error that says "Uncaught ReferenceError: quizz is not defined." <script setup> import { defineProps } from "vue"; import { useRouter } from "vue-router"; const router = us ...

Encountered an issue when attempting to retrieve an array of objects using axios

I have been encountering an error every time I try to make a get request with axios, while passing an array of hardcoded objects. The error message looks like this: https://i.sstatic.net/XsEle.png I am seeking assistance as I am new to react js. I believ ...

Navigating through iOS 7: Extracting a particular element from a json reply

I received a JSON response that appears like this: { "status": "success", "status_code": 200, "active": { "owned": [ { "id": "1", "name": "Chd Home", "type": "home", ...

Accessing JSON model from a different controller in SAPUI5

Exploring SAPUI5 is a new adventure for me, and I'm currently working on mastering Master and Detail pages through some exercises. In my setup, there are two views to work with: Master.view.xml and Detail.view.xml. The Master.view.xml displays a list ...

AngularJS allows for the execution of several asynchronous requests to a single API function, each with unique parameters

How can I asynchronously call 3 independent API methods so that as soon as any one of them has completed, I can work with the response without waiting for the others to finish? I am looking for a solution similar to System.Threading.Tasks in C#. var pro ...

construct a compressed and sorted collection of JSON objects in Ruby on Rails

As a beginner in the world of Rails, I have been working on flattening an array of JSON objects retrieved from the database in my controller. The goal is to create a flat data structure to use in my cross filter for some dc.js visualizations. So far, I&apo ...

Open the HTML document and access the file contents

I'm having trouble reading a text file from my computer onto a website. It works fine in Internet Explorer, but won't work in Chrome. I don't have much experience with HTML, so any help would be much appreciated! <html> <body> ...

Dividing ReactJS into different assemblies

I have a flexible .NET application that utilizes plugins to load controllers, views, and components from different assemblies. I am interested in learning React (completely new to me) and I have a question. Can React split its components into separate as ...

Generating JSON using Swift code involves constructing a JSON object and

I am struggling to create JSON in the following format: Order = { type_id:'1',model_id:'1', transfer:{ startDate:'10/04/2015 12:45', endDate:'10/04/2015 16:00', startPoint:'Ул. Момыш ...

Choose an image file to be uploaded for testing in Nightwatch on CircleCI

Currently, I am utilizing Nightwatch.js tests with test runs on a docker container in CircleCi. During the Nightwatch test on CircleCi, I am facing the challenge of uploading an image from the file system to my service. After some research, I came across ...

Shifting the position of personalized tabs using Jquery

I have created some basic HTML/CSS tabs and I want to move to the next tab by clicking a link at the bottom of every tab. HTML <ul class="tabs"> <li class="active"> <a href="#">Explainer (2mins)</a> <div class=" ...

JavaScript: How come my closure isn't functioning properly?

In the provided code snippet, only the last value of .enter_form input is being assigned to the last MYAPP.list[0].responses[MYAPP.score.round].form[key], where the variable key is the only element that changes. This issue seems to be caused by passing o ...

Utilizing Functions Within Arrays and HTML

My latest coding project involves creating a fun program where a button triggers a switch in colors for different images resembling a traffic light. Unfortunately, when I test the program by clicking the button, nothing seems to happen. Check out below fo ...

Following the mongoimport process, the MongoDB database does not display any collections

Recently, I delved into the world of MongoDB and mapReduce, but encountered a hurdle along the way. The MongoDB installation went smoothly. Next, I attempted to import a json file by executing these 2 commands before launching mongo in the terminal (worki ...

It is not possible to add items to an array

Attempting to retrieve data from the database using the callback method "getAllOrdersByUserId". The output is displayed below: [ TextRow { DishOrderId: 163, BagId: 'BPZDXT68148', DateCreated: 2021-05-27T03:55:05.000Z, Bags: & ...

Serialization of decimal numbers to JSON format for a Web API

I'm having an issue with retrieving JSON data that includes a float value of 10.0. Using AngularJS var replenishAccount = { ReloadThresholdAmount: parseFloat(vm.account.ReloadThresholdAmount), ReloadAmount: parseFloat(vm.account.ReloadAmount) }; va ...

Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is ...

Combining sub-objects under a shared parent in Javascript

In my data structure, I have parent objects with nested arrays of children. Here's an example: [ { "fullName": "Certificate", "checked": false, "children": [ { "type": "Certificate", "lastModifiedDate": "1971-01-01 ...