为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森栏 2021-04-13 15:14:20
我有两个模式:技能专长: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._idin的任何实例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文件?
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

您需要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 });

});


查看完整回答
反对 回复 2021-04-22
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信