gpt4 book ai didi

javascript - 有没有办法可以根据用户事件(例如评论)增加模型中的值?

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:52 24 4
gpt4 key购买 nike

每次用户在博客上发表评论时,我都会尝试增加用户当前的收入值。我正在编写一个加密程序,使用 Node 和 Express 作为后端,使用 MongoDB 作为数据库。我希望能够增加用户在平台中发表的每条评论所赚取的金额(当前)。

我尝试向用户模型添加“收入”字段,并将其设置为“数字”,因为这就是我实际需要的。然后我编写了几行代码来在应用程序(博客)中的任何位置发表评论时增加用户当前的数量,但它似乎不起作用。相反,它返回相同的数字,即 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.earning += 20,但没有指定哪个用户,甚至没有保存它。您需要使用 User.findOneAndUpdate$inc 来增加数值。

试试这个:

User.findOneAndUpdate({_id : req.user._id},{$inc : {earnings : 20}});

而不是

User.earnings = total;
User.earnings += 20;

只有在更新查询成功执行后,您才能验证它是否已更新。

此外,我建议创建您的评论文档并立即保存。另外,收入不会反射(reflect)在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);
}
})

关于javascript - 有没有办法可以根据用户事件(例如评论)增加模型中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com