如何从模式中删除项目,该模式是猫鼬中的对象数组? [英] How do I delete an item from a Schema which is an array of objects in mongoose?

查看:67
本文介绍了如何从模式中删除项目,该模式是猫鼬中的对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从架构中的简历列表中删除简历.

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

这篇关于如何从模式中删除项目,该模式是猫鼬中的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆