0

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

User.find({email: 'email@example.com'}).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@example.com'}).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?

WagnerMatosUK
  • 4,309
  • 7
  • 56
  • 95

3 Answers3

2

Actually

user[0].save();

will return a promise like you have done for User.find().then();

user[0].save() is an asynchronous call so the next call to find the user will run even though the user[0] is not updated in the database.

so place the second find command inside the then of save() function and you will get the updated user.

user[0].save().then(function(err){

    User.find(user[0].id).then(function (updateduser) {
    console.log(updateduser[0])
    });  
}))
selftaught91
  • 7,013
  • 3
  • 20
  • 26
1

Why you not use updated() method?

User.find({ email: 'email@example.com' })
    .then(function(user) {
        if (!user) return res.notFound();

        User.update({ eamil: 'eamil@example.com' }, {
                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();
    });
SkyQ
  • 380
  • 2
  • 9
0

First of all, you want to update only one user data because you are using user[0](I think).

So it is easy to use findOne().

Simple code

 User
    .findOne({email: 'email@example.com'})
    .exec(function(err,user){
       if(err || !user) {
         //handle  here
            }
       else {
             user.key1 = 'new_value';
             user.key2 = 'new_value';
             user.save(function(err){
                    if(err){
                               //handle error
                           }
                    console.log('updatedUser',user)  
               })
            }

  }) 

Thank you.

Yogesh Patel
  • 314
  • 1
  • 11