Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose updating a field in a MongoDB not working

I have this code

var UserSchema = new Schema({
    Username: {type: String, index: true},
    Password: String,
    Email: String,
    Points: {type: Number, default: 0}
});

[...]

    var User = db.model('User');
   /*
    * Function to save the points in the user's account
    */
    function savePoints(name, points){
        if(name != "unregistered user"){
        User.find({Username: name}, function(err, users){

            var oldPoints = users[0].Points;
            var newPoints = oldPoints + points;

            User.update({name: name}, { $inc: {Points: newPoints}}, function(err){
                if(err){
                    console.log("some error happened when update");
                }
                else{
                    console.log("update successfull! with name = " + name);
                    User.find({Username: name}, function(err, users) { 
                        console.log("updated : " + users[0].Points);
                    });
                }
            });

        });
    }
}

savePoints("Masiar", 666);

I would like to update my user (by finding it with its name) by updating his/her points. I'm sure oldPoints and points contain a value, but still my user keep being at zero points. The console prints "update successful".

What am I doing wrong? Sorry for the stupid / noob question.

Masiar

like image 614
Masiar Avatar asked Nov 21 '11 21:11

Masiar


People also ask

What is Upsert in Mongoose?

May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.

How do I update my Mongoose?

There are multiple ways to update documents in Mongoose. You can either use the save() , updateOne() , updateMany() , or findOneAndUpdate() method.

Can we change _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.


1 Answers

It seems you are doing a few unstandard things:

  • Use findOne instead of find if you want to load just one user
  • Calling Model.update should be done to update records that you have not loaded
  • $inc is adding oldPoints, so the new value will be 2*oldPoints + newPoints
  • You are using name as the conditional query instead of Username

I would rewrite the code into something like this:

User.findOne({Username: name}, function(err, user){
  if (err) { return next(err); }
  user.Points += points;
  user.save(function(err) {
    if (err) { return next(err); }
  });
});
like image 198
staackuser2 Avatar answered Oct 18 '22 13:10

staackuser2