猫鼬的前钩子:从数组中删除_id

时间:2019-04-08 14:54:56

标签: javascript node.js mongodb mongoose

我有两个模式:

技能:

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._idSkills.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数组中{@ {1}}删除用户{}? < / p>

1 个答案:

答案 0 :(得分: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 });
});