简体   繁体   English

如何删除猫鼬文件并从另一个模型中引用它?

[英]How to delete mongoose document and reference to it from another model?

I have the following schemas: 我有以下架构:

const userSchema = new Schema({
  email: {
    type: String,
    unique: true,
    lowercase: true
  },
  password: String,
  favorites: [{ type: Schema.Types.ObjectId, ref: 'image' }]
})

const imageSchema = new Schema({
  description: String,
  title: String,
  url: String
})

When I add an image I add a new image doc then I find the logged in user and update his favorites like so: 添加图像时,我添加了一个新的图像文档,然后找到了登录用户并更新了他的收藏夹,如下所示:

exports.addImage = function(req, res, next) {
  const email = req.user.email;
  imageData = req.body;
  imageData.url = req.body.media.m;

  const newImg = new Image(imageData);
  newImg.save()
    .then(function(image) {
      User.findOneAndUpdate(
        { email: email },
        { $push: { favorites: image._id } },
        function(err, doc) {
          if (err) { console.error(err) }
          res.status(201).send(doc)
        });
    });
}

When I remove a favorite I would like to delete the image and update the user reference to the image. 当我删除收藏夹时,我想删除该图像并更新对该图像的用户引用。 My code looks like this: 我的代码如下所示:

exports.deleteImageById = function(req, res, next) {
  const email = req.user.email;
  const id = req.body.id;

  Image.findOneAndRemove({ _id: id })
   .exec(function(err, removed) {
      User.findOneAndUpdate(
        { email: email },
        { $pull: { favorites: { _id: id } } },
        { new: true },
        function(err, removedFromUser) {
          if (err) { console.error(err) }
          res.status(200).send(removedFromUser)
        })
    })
}

when I test it out, the image is deleted, but the user reference in favorites never updates to reflect the changes. 当我对其进行测试时,该图像将被删除,但是收藏夹中的用户参考永远不会更新以反映所做的更改。 What is going wrong here? 这是怎么了?

There is no _id access prime with favourites, do this instead: 没有具有收藏夹的_id访问素数,而是这样做:

exports.deleteImageById = function(req, res, next) {
  const email = req.user.email;
  const id = req.body.id;

  Image.findOneAndRemove({ _id: id })
   .exec(function(err, removed) {
      User.findOneAndUpdate(
        { email: email },
        // no _id it is array of objectId not object with _ids
        { $pull: { favorites: id  } },
        { new: true },
        function(err, removedFromUser) {
          if (err) { console.error(err) }
          res.status(200).send(removedFromUser)
        })
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM