Search code examples
javascriptnode.jsmongodbmongoosekeystonejs

Data.model.updateItem is not a function TypeError: Data.model.updateItem is not a function


Error in keystone js using mongo : Vehicle.model.updateItem is not a function TypeError: Vehicle.model.updateItem is not a function .

The goal is to update the model using an object just like how I did create Items using the ff. code below.

CreateItems - Vehicle is the model. and postJson is the json array object.

keystone.createItems({
        Vehicle: postJson
      }, function (err, stats) {
        if (err) return res.json(err);
        res.json({
          data: stats.message
        });

        console.log("Succeeded!!")
      });

Now I am trying to update data on the model using an json array of object and with the unique id where itemToUpdate is the query to match the document I want to update and the fieldToUpdate is the object containing the field/fields you want a new value for. But it raises an error Vehicle.model.updateItem is not a function TypeError: Vehicle.model.updateItem is not a function

Update Code

  var itemToUpdate = {
              vin_no: value.vin_no
            }

            var fieldToUpdate = {
              Vehicle: value
            }

        Vehicle.model.updateItem(
          itemToUpdate,
          fieldToUpdate,
          function (err, stats) {
            if (err) return res.json(err);
            res.json({
              data: stats.message
            });

            console.log("Succeeded!!")
          })

Any idea how we can update data using objects. ?


Solution

  • you should use it like this

    // assuming value is object with all the fields. 
    var itemToUpdate = {
        vin_no: value.vin_no
    }
    
    Vehile.model.findOne(itemToUpdate, function(error, vehicleObject) {
    
        Vehicle.updateItem(
            vehicleObject,
            value,
            function (err) {
                // err can be Error object or an object with 'error' and/or 'detail' property
                if (err) return res.json(err);
    
                res.json({
                    status: "success"
                });
    
                console.log("Succeeded!!")
            })
    })
    

    if itemToUpdate has variable number of fields, you can add option to this call as

    var options = { field: 'vin_no, model_year, num_owners' }
    

    and pass this as Vehicle.updateItem(Vehicle.model, itemToUpdate, options, callback)