本文介绍了猫鼬更新MongoDB中的字段不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码
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);
我想通过以下方式更新我的用户(通过查找其名称):更新他/她的观点.我确定oldPoints和points包含一个值,但我的用户仍然保持零.控制台打印更新成功".
I would like to update my user (by finding it with its name) byupdating his/her points. I'm sure oldPoints and points contain avalue, but still my user keep being at zero points. The console prints"update successful".
我做错了什么?很抱歉这个愚蠢的/noob问题.
What am I doing wrong? Sorry for the stupid / noob question.
Masiar
推荐答案
似乎您在做一些不规范的事情:
It seems you are doing a few unstandard things:
- 如果只想加载一个用户,请使用
findOne
代替find
- 应该调用
Model.update
来更新尚未加载的记录 -
$inc
正在添加oldPoints,因此新值将为2 * oldPoints + newPoints - 您正在使用
name
作为条件查询,而不是Username
- Use
findOne
instead offind
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 ofUsername
我会将代码重写为如下形式:
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); }
});
});
这篇关于猫鼬更新MongoDB中的字段不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!