我有一个这样的架构:
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文档中填充了评论数组,我只想从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 })
答案 0 :(得分:0)
由于两个集合(srcStageMask
都不同,因此基于其他集合的值从一个集合中提取值根本行不通。因此,您首先必须从resort and review
集合中获取要删除的评论的ID,然后将其传递给review
$pull