How do I delete an item from a Schema which is an array of objects in mongoose?

孤人 提交于 2020-04-30 08:46:49

问题


I want to delete a resume from list of resumes in my schema.

I'm using mongoose(5.9.7) and express js.

Schema

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.

I'm creating a ref of resume in my ProfileSchema as well.

Profile Schema

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.


回答1:


Assuming remove is the instance of the resume that you want to delete (which you got using await Resume.findById(resumeId)):

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 } })

..or get the user, remove the corresponding entry in resumes, save the user.

2) Delete the resume using a simple remove:

await resume.remove()


来源:https://stackoverflow.com/questions/61297292/how-do-i-delete-an-item-from-a-schema-which-is-an-array-of-objects-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!