Search code examples
sails.jssails-mongo

How to update a model with Sails JS


Ok, I've got the following in one of my controllers:

User.find({email: '[email protected]'}).then(function (user) {

  user[0].field = 'new_value';
  user[0].field_2 = 'new_value';
  console.log(user[0], 'before saving');
  user[0].save();
  console.log(user[0], 'after saving');

});

If I console user[0] at this stage I can see the updated fields. However the changes were not saved to the db. If I do the following:

User.find({email: '[email protected]'}).then(function (user) {

  user[0].field = 'new_value';
  user[0].field_2 = 'new_value';
  user[0].save();

  User.find(user[0].id).then(function (updateduser) {

    console.log(updateduser[0])

  });

});

The updateduser does not have the updated fields... Why is that? How can should I proceed in this case?


Solution

  • Why you not use updated() method?

    User.find({ email: '[email protected]' })
        .then(function(user) {
            if (!user) return res.notFound();
    
            User.update({ eamil: '[email protected]' }, {
                    field: 'new_value',
                    field_2: 'new_value'
                })
                .then(function(updated_user) {
                    console.log(updated_user);
                    return res.ok();
                })
                .catch(function(err) {
                    sails.log.error(err);
                    return res.serverError();
                });
        })
        .catch(function(err) {
            sails.log.error(err);
            return res.serverError();
        });