基本上我所拥有的是位置索引。这是位置架构:
var locationSchema = new mongoose.Schema({
name: String,
gps: String,
image: String,
description: String,
catches: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Catch"
}
]
});
在这个模式中,我也有“捕获”基本上只是一个注释。这是以下的架构:
var catchSchema = mongoose.Schema({
species: String,
weight: String,
image: String,
catchlocation: String,
description: String,
timePosted: { type: Date, default: Date.now },
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
},
{timestamps: true}
);
我允许用户使用此路由删除“catch”(或注释):
app.delete("/locations/:id/catch/:catchid", isUserPost, function(req, res){
Catch.findByIdAndRemove(req.params.catchid, function(err){
if(err){
res.redirect("back");
} else {
req.flash("success", "Your catch has been deleted.");
res.redirect("/locations/" + req.params.id);
}
});
});
现在问题是,当删除“catch”(aka注释)时,它将从“catches”集合中删除,但ObjectId仍保留在该位置。使用mongoose,我如何从父元素中删除catch ObjectId?
你必须手动完成。我的建议是使用Mongoose中间件,使用预删除钩子:
catchSchema.pre('remove', function(next) {
// you can use 'this' to extract the _id this._id and find it in locations documents and remove where it appears
/** do the thing **/
next();
});