【问题标题】:How do I also delete the ObjectId from the parent element with mongoose?如何使用猫鼬从父元素中删除 ObjectId?
【发布时间】:2018-06-11 04:26:04
【问题描述】:

所以基本上我拥有的是位置索引。这是位置模式:

    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”(又名评论)被删除时,它会从“catch”集合中删除,但 ObjectId 仍保留在该位置。使用猫鼬,我如何从父元素中删除 catch ObjectId?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

您必须手动完成。我的建议是使用 Mongoose 中间件,带有 pre-remove 钩子:

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

【讨论】:

  • 甚至不知道它的存在。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-05-28
  • 2020-12-31
  • 2018-11-19
  • 2016-09-26
  • 2013-07-27
  • 2020-06-10
  • 1970-01-01
相关资源
最近更新 更多