简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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