【问题标题】:Mongoose remove objects from array of objects based on some filterMongoose 根据某些过滤器从对象数组中删除对象
【发布时间】:2020-11-21 22:30:00
【问题描述】:

我有这样的架构:

var resortSchema = new mongoose.Schema ({
name: String,
price: String,
reviews: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Review"
    }
]});


var reviewSchema = new mongoose.Schema({
    rating: {
        // Setting the field type
        type: Number,
        // Defining min and max values
        min: 1,
        max: 5,
        // Adding validation to see if the entry is an integer
        validate: {
            // validator accepts a function definition which it uses for validation
            validator: Number.isInteger,
            message: "{VALUE} is not an integer value."
        }
    },
    // author id and username fields
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    },
    // resort associated with the review
    resort: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Resort"
    }
});

在代码中,我在resorts 文档中填充了reviews 数组,我想从resort.reviews 数组中删除一些特定的评论(基于作者ID)。比如:

resort.reviews.pull({"author.id": someSpecificUserID});
resort.save();

但这不起作用。我该怎么做?

编辑: 我可以按特定用户 ID 找到所有评论,但我不知道如何按度假村过滤。 我试过这个:

console.log("req.user._id: " + typeof req.user._id); // object
console.log("req.params.id: " + typeof req.params.id); // string
console.log("ObjectId: " + typeof mongoose.Types.ObjectId(req.params.id));

var resortObjectID = mongoose.Types.ObjectId(req.params.id);

// Get ids of reviews matching a particular author
const reviews = await Review.find({ "author.id": req.user._id, "resort": resortObjectID });
console.log("reviews: " + reviews);     // reviews is []. if I remove "resort": resortObjectID I do get all the reviews of that user in all resorts. But I need to filter to only one resort.

//Pass review ids to $pull     // I am not sure if this works yet
await Resort.updateOne(
    { _id: req.params.id },
    { $pull: { reviews: { $in: reviews.map(x=>x._id) } } },
    { multi: true })

【问题讨论】:

    标签: arrays mongodb mongoose pull


    【解决方案1】:

    由于两个集合 (resort and review) 不同,因此根据其他集合的值从一个集合中提取值根本行不通。因此,您首先必须从 review 集合中获取要删除的评论的 ID,然后将它们传递给 $pull

     1. Get ids of reviews matching a particular author
        
        const reviews = await db.review.find({"author.id": <someSpecificUserID>}, {_id: 1});
    
     2. Pass review ids to $pull
    
        await db.resort.update(
        { },
        { $pull: { reviews: { $in: reviews.map(x=>x._id) } } },
        { multi: true })
      
    

    【讨论】:

    • 并非如此。我编辑了原始帖子并添加了更多代码。
    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2021-11-08
    相关资源
    最近更新 更多