如何从其他模型中删除mongoose文档并引用它?

时间:2016-06-07 00:06:42

标签: javascript node.js mongodb express mongoose

我有以下架构:

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

当我添加图像时,我添加了一个新的图像文档,然后我找到了登录用户并更新了他的收藏夹,如下所示:

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

当我删除收藏夹时,我想删除该图像并更新用户对该图像的引用。我的代码如下所示:

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

当我测试它时,图像被删除,但收藏夹中的用户引用永远不会更新以反映更改。这里出了什么问题?

1 个答案:

答案 0 :(得分:4)

收藏夹中没有_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)
        })
    })
}