0

When I update a model, waterlock .update() always return an array of objects, even if I set on criteria a primaryKey.

on my code

Ad.update({ id: req.param('id') }, {
    // desired attributed to be updated
}).exec(function(err, updatedRecord) {
    // updatedRecord is always an array of objects
});    

And in order to use the updatedRecord, I have to point out to 0 index like updatedRecord[0] which is something I consider not very clean. According to docs update() in sails, this is a common escenario.

Knowing that, I have 2 questions:

  1. Wouldn't be better that when you find one model return just a updated object for that model, not an array?

  2. If that is a convention, how could be overrided this function in order to return just an object instead of an array when .update() have only affected one record?

Leo
  • 1,051
  • 2
  • 13
  • 33

2 Answers2

1

it is a convention that it will update all the records that matches the find criteria, but as you are probably using a unique validation on model, it will probably return an array of 1 or 0. You need to do it on hand.

You can override methods in model, by implementing a method with same name as waterline default. But as you will need to completely rewrite the code, it is not viable. Neither changing waterline underlying code.

A solution will be creating a new function on your Ad model:

module.exports = {
  attributes: {
    adid: {
      unique: true,
      required: true
    },
    updateMe: {
    }
  },
  updateOne: function(adid, newUpdateMe, cb){
    Ad.update({ id: req.param('id') }, {
    // desired attributed to be updated
    }).exec(function(err, updatedRecord) {
        // updatedRecord is always an array of objects
        if (updatedRecord.length == 1){
          return cb(null, updatedRecord[0]);
        }
        return cb(null, {}); //also can error if not found.
    });    
  }
};

Also. Avoid using id as an model attribute (use other name), as some databases like mongodb already add this attribute as default and may cause conflicts with your model.

Gustavo Garcia
  • 1,905
  • 1
  • 15
  • 27
0

I dont think its possible with waterline. Its because update method is a generalized one, passing a primary key in where condition is always not the case.

Sapna Jindal
  • 412
  • 3
  • 11