我试图增加用户每次在博客上发表评论时的当前收入值。我正在用Node和Express为后端编写加密程序,用MongoDB为数据库编写加密程序。我想能够增加一个用户赚得的金额(当前)每评论他们在平台。
我尝试在用户模型中添加一个“收入”字段,并将其设置为Number,因为这正是我实际需要的。然后,我编写了几行代码,以增加用户在应用程序(blog)中任何地方发表评论时的当前数量,但这似乎不起作用。相反,它返回相同的数字,即20。我将它设置为每个注释添加20个,但它总是返回20而不是20,40,60...我的代码如下
// my model
var userSchema = new mongoose.Schema({
username: String,
firstName: String,
lastName: String,
earnings: 0,
email: String,
password: String
})
// my routes
router.post('/', middleware.isLoggedIn, (req, res) => {
// find blog using ID
Blog.findById(req.params.id, (err, blog) => {
if(err) {
console.log('Error:', err);
res.redirect('/blogs');
} else {
Comment.create(req.body.comment, (err, comment) => {
if(err) {
req.flash('error', 'Something went wrong');
console.log('Error:', err);
} else {
// add id
comment.author.id = req.user._id;
comment.author.username = req.user.username;
var total = Number(req.user.earnings);
// save comment
comment.save();
User.earnings = total;
User.earnings += 20;
blog.comments.push(comment);
blog.save();
res.redirect('/blogs/' + blog._id);
console.log(req.user.earnings);
console.log(User.earnings);
}
})
}
});
});
我希望收益值会增加,并为特定用户的每个评论保存
我认为您需要在创建评论后更新用户的文档。现在您只是执行user.rearning+=20
,但没有指定哪个用户,甚至没有保存它。您需要使用user.findoNeanDupdate
和$inc
来增加数字值。
试试看:
User.findOneAndUpdate({_id : req.user._id},{$inc : {earnings : 20}});
而不是
User.earnings = total;
User.earnings += 20;
并且只有在成功执行更新查询之后,您才能够验证它是否已更新。
此外,我会建议创建您的评论文档并保存它一次。而且,收入不会反映在req.user对象中,所以您需要自己修改它。‘查询应如下所示:
Comment.create(req.body.comment, (err, comment) => {
if(err) {
req.flash('error', 'Something went wrong');
console.log('Error:', err);
} else {
// add id
comment.author.id = req.user._id;
comment.author.username = req.user.username;
var total = Number(req.user.earnings);
// save comment
comment.save();
User.findOneAndUpdate({_id : req.user._id},{$inc : {earnings : 20}})
.then((err,user) => {
console.log(user.earnings)
});
blog.comments.push(comment);
blog.save();
res.redirect('/blogs/' + blog._id);
console.log(req.user.earnings); //i dont think your req.user object will be updated by itself
console.log(User.earnings);
}
})
您需要使用“$INC”运算符来增加任何数值。另外,使用“update”而不是“save”来更新文档。
参考:MongoDB文档