node.js - Mongoose:允许用户对每个期刊进行一次评论
问题描述
我有三个模式:
const journalSchema = new mongoose.Schema({
title: String,
category: String,
subcategory: String,
review: [{type: mongoose.Schema.Types.ObjectId, ref: 'Review'}],
link: String,
description: String,
subscribers: Number,
posts: Number,
image: {
data: Buffer,
contentType: String},
date: Date
});
const userSchema = new mongoose.Schema ({
username: String,
nickname: String,
password: String,
journal: [{type: mongoose.Schema.Types.ObjectId, ref: 'Journal'}],
googleId: String,
age: {type: Date},
gender: {type: String, enum: ["male", "female"]},
admin: Boolean,
role: String
});
const reviewSchema = new mongoose.Schema({
author: {type: mongoose.Schema.Types.String, ref: 'User'},
content: String,
date: Date,
rating: {type: Number, min: 1.0, max: 5.0}
});
const Journal = mongoose.model("Journal", journalSchema);
const User = mongoose.model("User", userSchema);
const Review = mongoose.model("Review", reviewSchema);
现在,任何用户都可以在同一期刊上留下任意数量的评论。我想做到这一点,以便用户每本期刊只能留下一条评论。
获取评论的发布路线:
app.post("/stats/review", function(req, res){
if(req.isAuthenticated()){
const userNickname = req.user.nickname;
const userId = req.user.id;
const userReview = req.body.journalReview;
const userRating = req.body.rating;
const journalId = req.body.journalId;
Journal.findById({_id: journalId}, function(err, journal){
Review.find({_id: {$in: journal.review}}, function(err, foundReview){
foundReview.forEach(function(review){
if(review.author == userNickname){
console.log("Review from this user already exists");
}
else{
var date = new Date();
const review = new Review();
review.author = userNickname;
review.content = userReview;
review.rating = userRating;
review.date = date;
review.save()
.then((result) =>{
Journal.findOneAndUpdate(
{_id: journalId},
{$push: {
review: review
}},
{useFindAndModify: false},
function(err, success){
if(err){
console.log(err);
}
else{
res.redirect("back");
}
}
);
})
.catch((error) =>{
console.log(error);
})
}
});
})
})
}
else{
res.redirect("/login");
}
});
是否可以使用 addToSet mongoose 方法来实现这一点?无法从类似问题中找到合适的解决方案。
解决方案
我想你需要在这里做一些检查
如果_id
评论字段中已经存在,则返回一些错误消息
推荐阅读
- android - 如何在折叠工具栏中实现选项卡布局的透明背景?并为折叠工具栏android提供背景或渐变效果?
- android - 如何不从我的网络视图导航到其他应用程序?
- ffmpeg - 使用单个命令在 ffmpeg 中转换和生成波形数据文件
- c++ - 如何防止在随机生成器中多次生成整数
- python - “PolynomialFeatures”对象没有“预测”属性
- c# - C# 使用 .docx 文本内容发送 Windows Mail
- javascript - 展平数组对象的数组
- django-orm - 如何使用 Django orm 进行此查询?
- python - 如何在没有numpy的情况下从数组(6,6,1)创建数组(1,6,6,1)?
- sql - oracle中GTT(全局临时表)更新缓慢