gpt4 book ai didi

javascript - Mongoose 预 Hook : pull _id from array on remove

转载 作者:行者123 更新时间:2023-11-30 14:05:09 26 4
gpt4 key购买 nike

我有两个模式:

技能:

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 文档包含与各种用户相关的技能(Skills.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 模式中实现一个预 Hook ,以便在删除用户时,Skills 中 user._id 的任何实例。 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);

我如何从 associatedUsers 数组中拉取要删除的用户的 ._id >技能文档?

最佳答案

您需要使用 $pull 进行更新运算符并指定 multi: true 以从 profile 集合中的所有文档中删除该值:

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

关于javascript - Mongoose 预 Hook : pull _id from array on remove,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55576222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com