Mongoose field update in 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 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 (finding him with his name) updating my points. I am sure that oldPoints and points contain but my user continues to remain at zero points. Console fingerprints "update successful."

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

Masiar

+6
source share
2 answers

It seems you are doing a few non-standard things:

  • Use findOne instead of find if you want to load only one user
  • A call to Model.update must be made to update records that you have not loaded.
  • $inc adds oldPoints, so the new value will be 2 * oldPoints + newPoints
  • You use name as a conditional request instead of Username

I would rewrite the code 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); } }); }); 
+10
source

follow my code boyfriend

  User.update({ username: "faibaa" }, { $inc: { point: 200000 } }, function(err,data){ return res.send(data); }); 
-1
source

Source: https://habr.com/ru/post/902057/


All Articles