首页 > 解决方案 > 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 方法来实现这一点?无法从类似问题中找到合适的解决方案。

标签: node.jsmongodbexpressmongooseejs

解决方案


我想你需要在这里做一些检查

如果_id评论字段中已经存在,则返回一些错误消息


推荐阅读