如何使用mongoose从父元素中删除ObjectId?

时间:2017-12-31 17:19:55

标签: node.js mongodb mongoose

基本上我所拥有的是位置索引。这是位置架构:

    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”(又名注释)时,它将从“catches”集合中删除,但ObjectId仍保留在该位置。使用mongoose,我如何从父元素中删除catch ObjectId?

1 个答案:

答案 0 :(得分:0)

你必须手动完成。我的消化是使用Mongoose中间件,使用pre-remove hook:

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();
});