如何从模式中删除项目,该模式是猫鼬中的对象数组?
我要从架构中的简历列表中删除简历.
I want to delete a resume from list of resumes in my schema.
我正在使用猫鼬(5.9.7)并表达js.
I'm using mongoose(5.9.7) and express js.
模式
const ResumeSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
fileLink: { type: String, required: true },
fileName: { type: String, required: true },
description: { type: String, required: true }
});
module.exports = Resume = mongoose.model("Resume", ResumeSchema);
我有一条路线来获取所有简历.
I have a route to fetch all the resumes.
我也在ProfileSchema中创建了简历的引用.
I'm creating a ref of resume in my ProfileSchema as well.
配置文件架构
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
resumes: [
{
type: Schema.Types.ObjectId,
ref: "Resume"
}
],
name: {
type: String,
required: true
},
});
module.exports = Profile = mongoose.model("Profile", ProfileSchema);
我不知道如何删除.我无法进行更新或拉动,因为它们似乎都适用于对象模式中的数组.
I don't know how to get ahead with delete. I couldn't make the update or pull work as they all seem to work for an array inside an object schemas.
假定remove
是您要删除(使用await Resume.findById(resumeId)
获得的)简历的实例:
Assuming remove
is the instance of the resume that you want to delete (which you got using await Resume.findById(resumeId)
):
1)删除引用:您可以使用 $pull
(要提取的值将是简历的_id
):
1) Delete the reference: you can do an update
with $pull
(the value to pull would be the resume's _id
):
// Assuming that `resume.user` is *not* populated
await User.update({ _id: resume.user }, { $pull: { resumes: resume._id } })
..或获取用户,在resumes
中删除相应的条目,保存用户.
..or get the user, remove the corresponding entry in resumes
, save the user.
2)使用简单的remove
删除简历:
2) Delete the resume using a simple remove
:
await resume.remove()