Mostafa Ghadimi
Mostafa Ghadimi

Reputation: 6736

.save() function doesn't work in mongoose

I'm trying to write a function that updates the score of the user using node.js and mongoose.

Here is my code:

router.post('/submitScore', (req, res) => {
    totalScore = Number(req.body.winnerScore) + Number(req.body.loserScore);
    // TODO: submit the score and redirect to another page
    User.find({teamName: req.body.winnerName}, (err, winner) => {

        // TODO: add special bonus for winner!
        winner.score = (winner.score / totalScore) * 100;
        winner.save((err) => {
            if (err) {
                console.log(err)
            }
        });
    })
    // TODO: add loser function
    console.log(typeof Number(req.body.winnerScore))
    res.redirect('/admin/');
});

I face with the following error:

  throw er; // Unhandled 'error' event
  ^

TypeError: winner.save is not a function

Note Whenever I console.log(winner), it prints the following

[ { score: 0,
_id: 5b963ef5c20ed241b87813bf,
teamName: 'mostafa',
faculty: 'مهندسی کامپیوتر',
email: '[email protected]',
password: '$2b$10$OqqagG.cwLE4RpGEn8voBOsHCRENgbivOejK9xmwdQ.TCAaVrYf0u',
__v: 0 } ]

but winner.score returns undefined where is the problem?

Upvotes: 1

Views: 65

Answers (3)

IftekharDani
IftekharDani

Reputation: 3729

Use findOne and then save

User.findOne({teamName: req.body.winnerName}, (err, winner) => {
      if(winner) //also check exists.
        // TODO: add special bonus for winner!
        winner.score = (winner.score / totalScore) * 100;
        winner.save((err) => {
            if (err) {
                console.log(err)
            }
        });
       } else {
//return not exists.
        }
    })

Upvotes: 1

robertklep
robertklep

Reputation: 203231

Notice how winner is an array, not an object, as indicated by the brackets ([ ... ]) surrounding it.

Use findOne instead of find if you're sure that the query will yield at most one result (also, don't assume that because you don't get an error, winner will be defined: if the query was succesful but didn't yield any results, winner will be null).

Upvotes: 1

DZDomi
DZDomi

Reputation: 1679

You did not check the err variable or the result of the find method; it looks like he can not found that entry in your database and therefore throws an error

Edit: After the updated post it looks like you try to call the save method on an array; so in order for your app to work you have to get the first element of the find for example:

winner = winner[0];

Or change your query to findOne() instead of find() if you are sure you will always just expect one result:

https://mongoosejs.com/docs/api.html#model_Model.findOne

Upvotes: 1

Related Questions