【问题标题】:Querying an array of a Mongo DB查询一个MongoDB的数组
【发布时间】:2020-07-14 07:32:34
【问题描述】:

目前,我正在从事一个在线训练营中的项目。这基本上是一个露营地的评论网站(我相信会有很多人知道我的意思)。从本质上讲,您可以注册自己,可以创建露营地,然后可以查看其他人。

我正在使用 mongo 数据库(如本课程所述)。

目前,我正在开发一条用户可以删除他/她的个人资料的路线。用户还能够成功删除其他露营地贡献和评论。但是,露营地的平均评分是根据露营地模型确定的。每当有人评论露营地时,他们的评论(评级、评论、姓名、用户 ID、日期等)

下面是露营地模型的视图:

const campgroundSchema = new mongoose.Schema({
    name: { 
        type: String, 
        required: "This field cannot be left blank"
    },
    image: String, 
    imageId: String, 
    description: String,
    price: String,
    createdAt: { type: Date, default: Date.now}, 
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId, 
            ref: "User", 
        }, 
        username: String
    },
    comments: [
        {
        type: mongoose.Schema.Types.ObjectId, 
        ref: "Comment"
        }
    ],
    slug: {
        type: String, 
        unique: true, 
        trim: true
    },
    reviews: [
        {
            type: mongoose.Schema.Types.ObjectId, 
            ref: "Review"
        }
    ], 
    rating: {
        type: Number, 
        default: 0
    }
});

以下是评论的模型:

var reviewSchema = new mongoose.Schema({
    rating:{
        //set the field type
        type: Number, 

        //Making the star rating required
        required: "Please provide a rating (1 to 5 stars)", 

        //Define minimum and maximum values:
        min: 1, 
        max: 5,

        //Add validation to ensure that entry is an integer: 
        validate:{
            validator: Number.isInteger, 
            message: "{VALUE} is not an integer value"
        }
    }, 
    text:{
        type: String, 
    },
    author: {
        id:{
            type: mongoose.Schema.Types.ObjectID, 
            ref: "User"
        }, 
        username: String
    }, 
    campground: {
        type: mongoose.Schema.Types.ObjectID, 
        ref: "Campground", 
    }
}, {
    //timestamps: mongoose assings createdAt and updatedAt to the schema. 
    timestamps:true
});

现在,每当我删除用户个人资料时,数组中的评论都会被删除(great),但是我需要链接到露营地以运行一个函数来给他们一个适当的评级。

删除用户的路径如下:

router.delete("/users/:id", middleware.isLoggedIn, (req, res)=>{
    User.findById(req.params.id, (err, user)=>{
        if(err){
            console.log(err); 
            req.flash("err", "UNABLE TO DELETE PROFILE " + err.message)
        }

        // delete campgrounds - finds campgrounds based on author.id and deletes them 
        Campground.deleteMany({"author.id": user.id}, (err)=>{ 
            if(err){
                console.log(err); 
            } 
        }); 

        //delete reviews - finds reviews based on author.id and deletes them 
        Review.deleteMany({"author.id": user.id}, (err)=>{
            if(err){
                console.log(err)
            }


    // WHERE I'M STUCK 
         Campground.findOne( { reveiws: {"author.id":user.id} }, {new: true}). exec((err, campground)=>{
                if(err){
                    console.log("ERROR:  " + err.message); 
                } else{  
                    console.log("CAMPGROUND:  " + campground); 
                }
                });

          }); 

        //delete profile picture from cloudinary
        try{
            cloudinary.v2.uploader.destroy(user.imageId);
            user.remove();
            res.redirect("/campgrounds");  
        } catch(err){
            if(err){
                req.flash("error", err.message);
                return res.redirect("back");  
            }
        }
    }); 
}); 

总之,我需要做的就是查询露营地数据库,以查找已被删除其个人资料的用户审查过的露营地。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您应该将用户 ID 作为 user._id 而不是 user.id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 2018-05-04
      • 2015-04-25
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      相关资源
      最近更新 更多