0

I try find one item by name, then update table and return updated result, but return didn't work. My code:

class addSongsToArtist {

    constructor(artistName) {

        Artist.findOne({
            name: artistName
        }).exec((err, data) => {
            if (err) console.log(err);

            data.name = 'updated name'
            data.save();

            return data // * not work 
        });
    }
}

Into exec method I see data with correct result, and into mongo console result saved. But return not works. I tried save changes into external variable and return result in Promise, but it not work too. Why it not works?

Matt Way
  • 32,319
  • 10
  • 79
  • 85
slava_slava
  • 636
  • 1
  • 10
  • 23
  • 1
    what do you mean by `not work`? It is an asynchronous method, so how are you trying to receive the value of `data` to use it? Can you share that piece of code? – Felipe Sabino Oct 25 '16 at 22:39
  • `data.save` is i/o so it takes time. You are return nothing before it Mongoose gets to play with it. Try `data.save(function(err){return data})` – Adam S Oct 25 '16 at 22:59
  • you need to understand async behavior in js. Have a look at http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Johannes Merz Oct 25 '16 at 23:04

2 Answers2

0

I have solution. Problem with construct method which return new object instance. Worked code:

class addSongsToArtist {
    constructor(artistName) {
      this.result = false
        Artist.findOne({
            name: artistName
        }).exec((err, data) => {
            if (err) console.log(err);

            data.name = 'updated name'
            data.save();
            this.result = data
        });
    }

  /**
  * need call in promise after call new addSongsToArtist()
  */
  getData() {
    return this.result
  }
}

And get data:

let findOne;
Promise.resolve()
  .then(()=>{
     findOne = new addSongsToArtist()
   })
  .then(()=>{
     findOne.getData()
   });
slava_slava
  • 636
  • 1
  • 10
  • 23
0

You use .save async function as sync function, try this instead :

constructor(artistName) {

    Artist.findOne({
        name: artistName
    }).exec((err, data) => {
        if (err || !data){
           console.log(err);
           return null;
        }
        else
        {
          data.name = 'updated name'
          data.save(function(err, savedDatas)
          {
             if(err || !savedDatas)
             {
                return null;
             }
             else
             {
                return savedDatas; // * not work 
             }
          });
        }
       });
Daphoque
  • 4,421
  • 1
  • 20
  • 31