我有两个模式:
技能:
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
文档拥有与各种users
(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
模式中实现预钩,以便在删除用户时,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
数组中{@ {1}}删除用户{1>}? < / p>
答案 0 :(得分:2)
您需要update
和$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 });
});