Mongoose pre hook:从数组中拉出_id删除

问题描述 投票:1回答:1

我有两个架构:

技能:

var mongoose = require("mongoose");

var SkillSchema = new mongoose.Schema({
    skill: { type: String },
    tally: { type: Number, default: 0 },
    associatedUsers: { type: Array },
});

module.exports = mongoose.model("Skills", SkillSchema);

轮廓:

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var profileSchema = new mongoose.Schema({ 
    username: String,
    password: String,
    skills: { type: Array }
    }
);

profileSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("Profile", profileSchema);

Skills文件拥有与各种usersSkills. Skills.associatedUsers)相关的技能:

{
    "_id" : ObjectId("5cab5c8788368eafb68b75a4"),
    "skill" : "cooking",
    "__v" : 0,
    "associatedUsers" : [
        ObjectId("5cab5c7d88368eafb68b75a0"),
        ObjectId("5cab546a7fb2b3a71c0404fa")
    ],
    "tally" : 0
}

Profile文档包含一系列技能:

{
    "_id" : ObjectId("5cab546a7fb2b3a71c0404fa"),
    "skills" : [
        "cooking", "cleaning"
    ],
    "__v" : 0,
    "username" : "deleteMe"
}

我正在尝试在Profile模式中实现预挂钩,以便在删除用户时,user._id中的任何Skills.associatedUsers实例也会被删除。

我尝试了以下内容,但它实际上删除了该技能的整个条目:

const Skills = require("./skills");


profileSchema.pre('remove', async function(){
    console.log("clearing user ID from skills model");
    await Skills.remove({associatedUsers: { $in: this._id } });

});

module.exports = mongoose.model("Profile", profileSchema);

我如何从pull文档中的._id数组中associatedUsers被删除用户的Skills

javascript node.js mongodb mongoose
1个回答
2
投票

你需要update$pull运算符,并指定multi: trueprofile集合中的所有文档中删除该值:

profileSchema.pre('remove', async function(){
    console.log("clearing user ID from skills model");
    await Skills.update({}, { $pull: { associatedUsers: { $in: this._id } } }, { multi: true });
});
© www.soinside.com 2019 - 2024. All rights reserved.