Nishchit
Nishchit

Reputation: 19074

Why is Model.save() not working in Sails.js?

Save() giving me error like "Object has no method 'save'"

Country.update({id:req.param('country_id')},model).exec(function(err,cntry){

         if(err) return res.json(err);

         if(!cntry.image){

               cntry.image = 'images/countries/'+filename;
               cntry.save(function(err){ console.log(err)});
         }
})

Any Idea about how to save model within update query . ??

Upvotes: 1

Views: 4812

Answers (2)

sgress454
sgress454

Reputation: 24948

Assuming you're using Waterline and sails-mongo, the issue here is that update returns an array (because you can update multiple records at once), and you're treating it like a single record. Try:

Country.update({id:req.param('country_id')},model).exec(function(err,cntry){

         if(err) return res.json(err);

         if(cntry.length === 0) {return res.notFound();}

         if(!cntry[0].image){

               cntry[0].image = 'images/countries/'+filename;
               cntry[0].save(function(err){ console.log(err)});
         }
});

This seems to me an odd bit of code, though; why not just check for the presence of image in model before doing Country.update and alter model (or a copy thereof) accordingly? That would save you an extra database call.

Upvotes: 2

giorni
giorni

Reputation: 158

When using mongoose (3.8) to update the database directly the callback function receives 3 parameters, none of then is a mongoose object of the defined model. The parameters are:

  • err is the error if any occurred
  • numberAffected is the count of updated documents Mongo reported
  • rawResponse is the full response from Mongo

The right way is, first you fetch and then change the data:

Country.findOne({id: req.param('country_id')}, function (err, country) {
  // do changes
})

Or using the update method, the way you intended:

Country.update({id: req.param('country_id'), image: {$exists: false}}, {image: newValue}, callback) 

Upvotes: 1

Related Questions